Rails 3 migrations: Adding reference column? Rails 3 migrations: Adding reference column? ruby-on-rails ruby-on-rails

Rails 3 migrations: Adding reference column?


If you are using the Rails 4.x you can now generate migrations with references, like this:

rails generate migration AddUserRefToProducts user:references

like you can see on rails guides


EDIT: This is an outdated answer and should not be applied for Rails 4.x+

You don't need to add references when you can use an integer id to your referenced class.

I'd say the advantage of using references instead of a plain integer is that the model will be predefined with belongs_to and since the model is already created and will not be affected when you migrate something existing, the purpose is kind of lost.

So I would do like this instead:

rails g migration add_user_id_to_tester user_id:integer

And then manually add belongs_to :user in the Tester model


Please note that you will most likely need an index on that column too.

class AddUserReferenceToTester < ActiveRecord::Migration  def change    add_column :testers, :user_id, :integer    add_index  :testers, :user_id  endend