Guilherme
Guilherme

Reputation: 1103

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

Upvotes: 9

Views: 3414

Answers (5)

Lu&#237;s Ramalho
Lu&#237;s Ramalho

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

Rajarshi Das
Rajarshi Das

Reputation: 12320

Your migration should be

rails generate migration AddUserRefToPosts user:references 

Upvotes: 3

medBouzid
medBouzid

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

Marek Lipka
Marek Lipka

Reputation: 51151

How about this:

def change
  change_table :posts do |p|
    p.references :user, index: true
  end
end

Upvotes: 2

crackedmind
crackedmind

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

Related Questions