How ActiveRecords create tables

Cris Shupp
Wed, 23 Sep 2009 19:33:24 -0000

I''ll start off by saying I am new to Ruby and Rails...

Suppose I run the following;

$ script/generate model person


which creates:

class CreatePeople < ActiveRecord::Migration
  def self.up
    create_table :people do |t|

      t.timestamps
    end
  end

  def self.down
    drop_table :people
  end
end


I added in some code (the author instructs me to) such that it now
reads:

class CreatePeople < ActiveRecord::Migration
  def self.up
    create_table :people do |t|
      t.string :name, :type, :email, :camera #ADDED IN
      t.timestamps
    end
  end

  def self.down
    drop_table :people
  end
end

I do not understand, at a ruby level, what is going on.  It appears I
have a class (static) method called up.  The first thing I am doing is
calling Migration''s create_table method.  This leads to question 1:

1:) Migration does not have create_table method.  How is Ruby finding
create_table?

Now the create_table method appears to accept two parameters.  The first
being a symbol, and the second being a code block.

I am assuming that the only thing obtainable from this code block is the
last line t.timestamps, as the last line is returned in ruby.

So question number two:

2:  What does this line even do?
t.string :name, :type, :email, :camera #ADDED IN

What is t being passed in?  why no comma between t.string and :name.


And my final question...

How come I cannot write the code as follows (Aptana will not compile
it)?
  def self.up
    create_table (:people,{|t|
      t.string :name, :type, :email, :camera
      t.timestamps
    })
  end


BTW as I hunt I do see this in Migration:

def method_missing(method, *arguments, &block)

It is taunting me.

Feel free to respond to me like I am four.  You could try to insult me
but you would fail :-)

Thanks,

Cris