Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method 'add_reference'

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

like image 346
Guilherme Carlos Avatar asked Aug 29 '13 11:08

Guilherme Carlos


5 Answers

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.

like image 136
Luís Ramalho Avatar answered Nov 15 '22 20:11

Luís Ramalho


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

like image 30
medBouzid Avatar answered Nov 15 '22 20:11

medBouzid


Your migration should be

rails generate migration AddUserRefToPosts user:references 
like image 28
Rajarshi Das Avatar answered Nov 15 '22 21:11

Rajarshi Das


How about this:

def change
  change_table :posts do |p|
    p.references :user, index: true
  end
end
like image 40
Marek Lipka Avatar answered Nov 15 '22 19:11

Marek Lipka


This method apperead in Rails 4.0

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

like image 24
crackedmind Avatar answered Nov 15 '22 19:11

crackedmind