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 => ' を試してください。次のいずれかですか?」
何か案は?