Rails 3.2.11에서 두 모델 간의 다 대다 관계를 만들려고합니다.Rails의 many to many 관계
사용자는 여러 인시던트와 연관 될 수 있으며 반대의 경우도 마찬가지입니다.
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
조인 테이블 : 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
에 대한
class IncidentParticipant < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection
t.belongs_to :participant, class_name: "User"
t.belongs_to :participated_incident, class_name: "Incident"
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
하하 문제 없습니다. 나는 당신이 nil 클래스를위한 nomethoderror를 얻지 못했기 때문에 메소드로 존재한다고 생각합니다. 그렇지 않으면 아마 그것을 잡았을 것입니다. :) – agmcleod