Reputation: 171341
The command
rails generate scaffold Post name:string title:string content:text
generated the following 20101109001203_create_posts.rb
file:
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.string :name
t.string :title
t.text :content
t.timestamps
end
end
def self.down
drop_table :posts
end
end
Since I'm new to Ruby (just read one book), I have some questions on this block of code:
What does self.
means in self.up
and self.down
? How it differs from simply up
and down
?
What does all these colons (:
) means in :posts
, :name
, etc. ? Is that just a part of the variable name ?
What does t.string :name
means ? Is that a call to string
function on object t
with parameter :name
?
Thanks a lot!!
Upvotes: 2
Views: 619
Reputation:
def self.up defines the class method up. When rails runs that migration it will call CreatePosts.up. The alternative being def up which would define an instance method which could be called with CreatePosts.new.up.
:name (for example) is an example of a Symbol. As symbol is similar to a string, but stripped down to the point where there's almost nothing there but the text. In this case they're just using it to tell the #string method what you want the column to be called.
You got that exactly right.
You may find this helpful.
Upvotes: 1
Reputation: 42865
self
is the migration file and up
and down
apply and reverse the migration respectively.t.sting :name
means create a column on the current migration object with name name
and type string
Upvotes: 1
Reputation: 370162
If you define a method using def foo
, you're creating an instance method called foo
. I.e. if you have an instance of class CreatePosts
you can do the_instance.foo
. However by doing def self.foo
(or alternatively def CreatePosts.foo
which does the same thing, because self == CreatePosts
in the class ... end
-block), you're defining a singleton method which is only available on CreatePosts
itself. I.e. it is called as CreatePosts.foo
not the_instance.foo
(this is somewhat similar to static methods in other languages, but not quite because you can use the same syntax to define singleton methods on objects that aren't classes).
:name
has nothing to do with any variable called name
. It's a symbol literal, which is kind of like an interned immutable string (though the Symbol class does not define any methods for string-manipulation). You can think of symbols as some sort of mini-strings which are used when you just need to label something and don't need to do string manipulation.
Yes, exactly.
Upvotes: 3