9

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

Guilherme Carlos
  • 1,057
  • 1
  • 15
  • 28
  • this might help? http://stackoverflow.com/questions/4954969/rails-3-migrations-adding-reference-column – dax Aug 29 '13 at 11:44

5 Answers5

16

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.

Luís Ramalho
  • 9,209
  • 4
  • 45
  • 63
3

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

medBouzid
  • 6,333
  • 8
  • 46
  • 72
3

Your migration should be

rails generate migration AddUserRefToPosts user:references 
Rajarshi Das
  • 12,984
  • 3
  • 43
  • 57
2

How about this:

def change
  change_table :posts do |p|
    p.references :user, index: true
  end
end
Marek Lipka
  • 48,573
  • 7
  • 81
  • 87
1

This method apperead in Rails 4.0

I think you may create some monkey patch with this functionality for Rails 3.2

crackedmind
  • 908
  • 6
  • 14