我試圖在Rails 3.2.11中的兩個模型之間創建多對多的關係。Rails中的多對多關係
用戶可以與許多事件相關聯,反之亦然。
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
那麼,爲什麼不軌得到這個關係?當我嘗試在我的視圖中執行@ incident.participants時,出現此錯誤:
"Could not find the source association(s) :participant or :participants in model IncidentParticipant. Try 'has_many :participants, :through => :incident_participants, :source => '. Is it one of ?"
任何想法?
哦,我的上帝......我認爲是時候離開今天的工作:)謝謝! – Linus 2013-02-08 15:07:06
哈哈沒問題。我認爲作爲一種方法存在,因爲你沒有得到一個nil類的nomethoderror,否則你可能會抓住它。 :) – agmcleod 2013-02-08 15:07:57