I happen to be working on an app that also has an Entry
model / entries
table. Here's my migration:
class CreateEntries < ActiveRecord::Migration
def self.up
create_table :entries do |t|
t.string :title
t.text :entry
# ...
end
end
def self.down
drop_table :entries
end
end
Very similar to what you're looking at.
Fist off, first line, declaring a class called CreateEntries
which extends ActiveRecord::Migration
.
Next, declaring a class method called up()
. A class method, as opposed to an instance method belongs to the class rather than to specific objects of the class. It's the "self
" keyword that causes it to be a class method.
Next calling create_table()
and passing it two things:
A symbol (":entries
") which, as mentioned above, is like a String literal. This tells ActiveRecord what the table it creates should be called. Let's say you typed this code by hand -- forget about generators for a minute. You typed ":entries
" because you know that by convention tables in a Rails app are named with plural nouns, and you know that the model class that hooks up to this table will be called Entry
.
Also passing a block.
A block can be enclosed by...
`do ... end`
or by
`{ ... }`
A block can take parameters enclosed by two "|
"s. In this case the create_table
method is passing to the block an object of class TableDefinition
, so to answer one of your questions, t
is the var holding that object. Then inside the block, we're calling various instance methods of TableDefinition
.
Where did the TableDefinition
object come from? That happens in the create_table()
method. It contains the code that instantiates a new TableDefinition
object and "yields" it to the block....
ActiveRecord source code...
def create_table(table_name, options = {})
table_definition = TableDefinition.new(self)
table_definition.primary_key(options[:primary_key] || "id") unless options[:id] == false
yield table_definition
# ...
end