2013-02-08 5 views
0

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 ?"

어떤 아이디어?

답변

1

t.belongs_to을 꺼내 belongs_to으로 바꿔보십시오.

+0

오 세상에 .... 오늘은 일을 떠날 때가되었다고 생각합니다. :) 고마워요! – Linus

+0

하하 문제 없습니다. 나는 당신이 nil 클래스를위한 nomethoderror를 얻지 못했기 때문에 메소드로 존재한다고 생각합니다. 그렇지 않으면 아마 그것을 잡았을 것입니다. :) – agmcleod

0

many to many 연관을 만들려면 연관 테이블을 만드는 것이 좋습니다. 즉, 정렬 중간 테이블을 가리키는 두 개의 1-M 관계를 갖게됩니다.

첫 번째 모델에서 : 두 번째 모델에서

class Example < ActiveRecord::Base 
    has_and_belongs_to_many :example2 
end 

: 예를 들어

class Example2 < ActiveRecord::Base 
    has_and_belongs_to_many :example 
end 

은 그럼 당신은 함께 두 테이블을 연결하는 마이그레이션을 작성해야합니다 :

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

그럼 레일스 마술이 작동하도록하십시오. 자세한 내용은 guides을 확인하십시오.