我正在尝试在 Rails 3.2.11 中的两个模型之间创建多对多关系。
一个用户可以与许多事件相关联,反之亦然。
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
事件参与者表
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 => '。它是其中之一吗?”
有任何想法吗?