For Rails 4
The generator accepts column type as references (also available as belongs_to
).
This migration will create a user_id
column and appropriate index:
$ rails g migration AddUserRefToProducts user:references
generates:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :products, :user, index: true
end
end
http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration
For Rails 3
Helper is called references (also available as belongs_to
).
This migration will create a category_id
column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the _id
for you.
change_table :products do |t|
t.references :category
end
If you have polymorphic belongs_to
associations then references will add both of the columns required:
change_table :products do |t|
t.references :attachment, :polymorphic => {:default => 'Photo'}
end
Will add an attachment_id column and a string attachment_type
column with a default value of Photo
.
http://guides.rubyonrails.org/v3.2.21/migrations.html#creating-a-standalone-migration