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
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.
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
Your migration should be
rails generate migration AddUserRefToPosts user:references
How about this:
def change
change_table :posts do |p|
p.references :user, index: true
end
end
This method apperead in Rails 4.0
I think you may create some monkey patch with this functionality for Rails 3.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With