Ruby on rails 在rails 4中创建多对多关系
如何在迁移类中创建一个关系表,使两个引用都在唯一索引中使用Ruby on rails 在rails 4中创建多对多关系,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,如何在迁移类中创建一个关系表,使两个引用都在唯一索引中使用 class CreateDiagnosticHypotheses < ActiveRecord::Migration def change create_table :diagnostic_hypotheses, :id => false do |t| t.references :accident_indication, index: true t.references :forms, i
class CreateDiagnosticHypotheses < ActiveRecord::Migration
def change
create_table :diagnostic_hypotheses, :id => false do |t|
t.references :accident_indication, index: true
t.references :forms, index: true
t.timestamps null: false
end
add_foreign_key :diagnostic_hypotheses, :accident_indications
add_foreign_key :diagnostic_hypotheses, :forms, column: :diagnostic_hypothesis_id
end
end
class CreateDiagnosticyPothesesfalse do | t|
t、 参考:事故指示,索引:真
t、 参考:表单,索引:true
t、 时间戳null:false
终止
添加外键:诊断假设:事故指示
添加外部关键字:诊断假设,:表单,列::诊断假设id
终止
终止
当我运行rakedb:migrate时,它会尝试创建单独的索引。如何仅创建一个同时包含:事故指示和:表单引用的唯一索引?您可以创建唯一的复合索引:
class CreateDiagnosticHypotheses < ActiveRecord::Migration
def change
create_table :diagnostic_hypotheses, :id => false do |t|
t.references :accident_indication
t.references :forms
t.timestamps null: false
end
add_index :diagnostic_hypotheses, [:accident_indication_id, :forms_id], :unique => true
add_foreign_key :diagnostic_hypotheses, :accident_indications
add_foreign_key :diagnostic_hypotheses, :forms, column: :diagnostic_hypothesis_id
end
end
class CreateDiagnosticyPothesesfalse do | t|
t、 参考:事故指示
t、 参考资料:表格
t、 时间戳null:false
终止
添加索引:诊断假设,[:事故\指示\ id,:表格\ id],:唯一=>真
添加外键:诊断假设:事故指示
添加外部关键字:诊断假设,:表单,列::诊断假设id
终止
终止
但是,我自己没有尝试过,但我认为您已经有了想法。唯一的问题是,它会生成一个很长的索引名,您必须手动提供一个索引名。这似乎有点奇怪,它没有提供一种通过引用名而不是生成的列名创建复合索引的方法,但这没关系。