1

I have gone through some of similar question people asked but couldn't find the appropriate solution for it. I have also seen some people using this method - add_foreign_key

 class CreateTaskLists < ActiveRecord::Migration
  def change
    create_table :task_lists do |t|
      t.string :name
      t.references :user
      t.timestamps
    end
    add_foreign_key :task_lists, :users
  end
end

but it is throwing undefined method error.

undefined method `add_foreign_key' for 
#<CreateTaskLists:0x007ffe9a5cd578>
/Users/sushilkumar/.rvm/gems/ruby-2.2.3/gems/
activerecord-4.0.0/lib/active_record/
migration.rb:624:in `block in method_missing'

How to add foreign key in rails migration with different table name I don't know, How does this work for them?

Community
  • 1
  • 1
sushilprj
  • 2,203
  • 1
  • 14
  • 19

4 Answers4

2

You can simply try this way using references

class CreateTaskLists < ActiveRecord::Migration
  def change
    create_table :task_lists do |t|
      t.string :name
      t.references :user, index: true
      t.timestamps
    end
    add_foreign_key :task_lists, :users
  end
end
sushilprj
  • 2,203
  • 1
  • 14
  • 19
Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74
  • I have updated the migration but it is still throwing error. Is there any gem required to enable add_foreign_key method? – sushilprj Oct 08 '15 at 08:00
  • http://api.rubyonrails.org/v4.2.0/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key – Rajarshi Das Oct 08 '15 at 08:27
  • Thanks Rajarshi, It was my mistake. I was using rails 4.0.0 version. Now it is working .. :) – sushilprj Oct 08 '15 at 09:43
1
class CreateTaskLists < ActiveRecord::Migration
  def change
    create_table :task_lists do |t|
      t.string :name
      t.references :user, index: true
      t.timestamps
    end
    add_foreign_key :task_lists, :users
  end
end

try this

Vrushali Pawar
  • 3,753
  • 1
  • 13
  • 22
1

Did you meant to reference the table User and not Users? If so, you must use the singular (:user) when making a reference:

class CreateTaskLists < ActiveRecord::Migration
 def change
   create_table :task_lists do |t|
     t.string :name
     t.references :user
     t.timestamps
   end
   add_foreign_key :task_lists, :users
 end

end

Aliou
  • 1,065
  • 11
  • 17
0

Hope this will work for you.

class CreateTaskLists < ActiveRecord::Migration
  def change
    create_table :task_lists do |t|
      t.string :name
      t.references :user
      t.timestamps
    end
    add_foreign_key :users, :task_lists
  end
end
sushilprj
  • 2,203
  • 1
  • 14
  • 19
CreativePS
  • 1,105
  • 7
  • 15