如何在活动记录中正确添加外键?

时间:2015-03-23 14:15:49

标签: ruby ruby-on-rails-4 activerecord

我试图在多个表中创建一些引用完整性,并且正在绊倒添加外键的位置。该语句最多被忽略,最糟糕的是它会抛出错误。

class CreateCantons < ActiveRecord::Migration
def change
create_table :cantons do |t|
  t.integer :canton_id
  t.string :canton_name

  t.timestamps null: false
end
end
end

class CreateResources < ActiveRecord::Migration
def change
create_table :resources do |t|
  t.integer :resource_id
  t.string :resource_name
  t.integer :type_id
  t.integer :canton_id
  t.string :url
  t.string :address
  t.string :city
  t.string :state
  t.string :zip
  add_foreign_key :cantons, :canton_id #ignored
  add_foreign_key :types, :type_id #ignored

  t.timestamps null: false
end
end
end

class CreateResourceContacts < ActiveRecord::Migration
def change
create_table :resource_contacts do |t|
  t.integer :contact_id
  t.integer :resource_id
  add_foreign_key :resources, :resource_id
  add_foreign_key :contacts, :contact_id

  t.timestamps null: false
end
end
end

在前面添加一个t会抛出错误

t.add_foreign_key :contacts, :contact_id #error

如何正确使用此命令?

1 个答案:

答案 0 :(得分:3)

您需要将foreign_keys移到create table之外

class CreateResources < ActiveRecord::Migration
  def change
    create_table :resources do |t|
      t.integer :resource_id
      t.string :resource_name
      t.integer :type_id
      t.integer :canton_id
      t.string :url
      t.string :address
      t.string :city
      t.string :state
      t.string :zip

      t.timestamps null: false
    end

    add_foreign_key :resources, :cantons
    add_foreign_key :resources, :types 

  end
end

请参阅http://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key

而且你还需要告诉它你要添加它的表格。