I am new to ruby on rails, could anybody explain what does the symbol ‘:’ mean, what would be ‘validates’ and ‘create_table’? So much confused…
class Post < ActiveRecord::Base
validates :name, :presence => true
validates :title, :presence => true, :length => {:minimum => 5}
end
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :name
t.string :title
t.text :content
t.timestamps
end
end
end
The colon character (
:) is the beginning of a syntax literal for a Ruby “Symbol”:Symbols are like strings but they are “interned”, meaning the Ruby interpreter only has a single copy of it in memory despite multiple possible references (whereas there can be many equivalent strings in memory at once).
The ‘
validates‘ token in your example above is a class method (of something in the class hierarchy of the “Post class”) that is being called with a symbol argument (:name) and a hash argument with a single key/value pair of:presence => true.The ‘
create_table‘ token is a method which is being called with a single argument (the symbol “:posts“) and is given a block which takes a single argument “t” (do |t| ... end).