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 inself.upandself.down? How it differs from simplyupanddown? -
What does all these colons (
:) means in:posts,:name, etc. ? Is that just a part of the variable name ? -
What does
t.string :namemeans ? Is that a call tostringfunction on objecttwith parameter:name?
Thanks a lot!!
If you define a method using
def foo, you’re creating an instance method calledfoo. I.e. if you have an instance of classCreatePostsyou can dothe_instance.foo. However by doingdef self.foo(or alternativelydef CreatePosts.foowhich does the same thing, becauseself == CreatePostsin theclass ... end-block), you’re defining a singleton method which is only available onCreatePostsitself. I.e. it is called asCreatePosts.foonotthe_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).:namehas nothing to do with any variable calledname. 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.