Reputation: 1103
I'm trying to add a user reference to my post tables with following code:
class AddUserIdToPosts < ActiveRecord::Migration
def change
add_reference :posts, :user, index: true
end
end
but I've received an error message:
undefined method 'add_reference'
Anyone knows how to solve this?
I'm using Rails 3.2.13
Upvotes: 9
Views: 3414
Reputation: 10198
In Rails 3 you must do it like so
class AddUserIdToPosts < ActiveRecord::Migration
def change
add_column :posts, :user_id, :integer
add_index :posts, :user_id
end
end
Only in Rails 4 you can do it the way you posted.
Upvotes: 16
Reputation: 12320
Your migration should be
rails generate migration AddUserRefToPosts user:references
Upvotes: 3
Reputation: 8372
add_reference is specific to rails 4.0.0, so you should try this instead :
class AddUserIdToPosts < ActiveRecord::Migration
def change
add_column :posts, :user_id, :integer
add_index :posts, :user_id
end
end
this is a great post about this subject
Upvotes: 3
Reputation: 51151
How about this:
def change
change_table :posts do |p|
p.references :user, index: true
end
end
Upvotes: 2
Reputation: 928
This method apperead in Rails 4.0
I think you may create some monkey patch with this functionality for Rails 3.2
Upvotes: 1