我试图在多个表中创建一些引用完整性,但在添加外键的位置上遇到了障碍。充其量该语句会被忽略,最坏的情况是它会引发错误。
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
如何正确使用这个命令?
最佳答案
您需要将外键移到创建表之外
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
而且您还需要告诉它您要将其添加到哪些表中。
关于ruby - 如何在事件记录中正确添加外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29212536/