sushilprj
sushilprj

Reputation: 2243

How to add database level foreign key in the migration file in rails 4.2?

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?

Upvotes: 1

Views: 280

Answers (4)

Rajarshi Das
Rajarshi Das

Reputation: 12340

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

Upvotes: 2

CreativePS
CreativePS

Reputation: 1093

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

Upvotes: 0

Aliou
Aliou

Reputation: 1105

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

Upvotes: 1

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

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

Upvotes: 1

Related Questions