Tyler DeWitt Tyler DeWitt - 4 months ago 26
Ruby Question

t.belongs_to in migration

I was using Ryan Bates's source code for railscasts #141 in order to create a simple shopping cart. In one of the migrations, he lists

class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.belongs_to :category
t.string :name
t.decimal :price
t.text :description
t.timestamps
end
end

def self.down
drop_table :products
end
end


Here is the Product model:

class Product < ActiveRecord::Base
belongs_to :category
end


What is the
t.belongs_to :category
line? Is that an alias for
t.integer category_id
?

Answer

The t.belongs_to :category is just a special helper method of rails passing in the association.

If you look in the source code belongs_to is actually an alias of references

Comments