0

Rails 3.2.11 の 2 つのモデル間に多対多の関係を作成しようとしています。

ユーザーは多くのインシデントに関連付けることができ、その逆も可能です。

class User < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection

  has_many :incident_participants, foreign_key: "participant_id"
  has_many :participated_incidents, through: :incident_participants

end


class Incident < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection

  has_many :incident_participants, foreign_key: "participated_incident_id"
  has_many :participants, through: :incident_participants

end

結合テーブル:

class IncidentParticipant < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection

  t.belongs_to :participant, class_name: "User"
  t.belongs_to :participated_incident, class_name: "Incident"
end

IncidentParticipants の表

  create_table "incident_participants", :force => true do |t|
    t.integer  "participant_id"
    t.integer  "participated_incident_id"
    t.datetime "created_at",               :null => false
    t.datetime "updated_at",               :null => false
  end

では、なぜ Rails はこの関係を取得しないのでしょうか? ビューで @incident.participants を実行しようとすると、次のエラーが発生します。

「モデル IncidentParticipant でソース アソシエーション :participant または :participants が見つかりませんでした。'has_many :participants, :through => :incident_participants, :source => ' を試してください。次のいずれかですか?」

何か案は?

4

2 に答える 2

1

を取り出して、t.belongs_toに置き換えてみてくださいbelongs_to

于 2013-02-08T15:02:08.750 に答える
0

多対多の関連付けを作成するには、関連付けテーブルの作成を検討する必要があります。つまり、ソート仮テーブルを指す 2 つの 1-M リレーションシップがあることになります。例えば:

最初のモデルでは:

class Example < ActiveRecord::Base
  has_and_belongs_to_many :example2
end

2 番目のモデルでは:

class Example2 < ActiveRecord::Base
  has_and_belongs_to_many :example
end

次に、2 つのテーブルをリンクする移行を作成する必要があります。

class CreateTableExamplesExamples2 < ActiveRecord::Migration
  create_table :examples_examples2 do |t|
    t.integer :example_id
    t.integer :example2_id
  end
end

あとは、Rails マジックを機能させるだけです。詳細については、ガイドをご覧ください。

于 2013-02-08T16:01:24.020 に答える