在rails 4中创建多对多的关系

时间:2015-05-31 14:00:29

标签: 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, 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

当我运行rake db:migrate时,它会尝试创建单独的索引。如何只使用:accident_indication和:forms references?

创建一个唯一索引

1 个答案:

答案 0 :(得分:0)

您可以创建唯一的综合索引:

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

然而,我并没有亲自尝试,但我认为你已经有了这个想法。