1

제 질문은 프로그래밍과는 달리 명명 규칙과 관련이 있습니다.동일한 모델에 두 개의 관계가있을 때 레일 규칙 명명법

사용자가 새 기사를 만들 수있는 응용 프로그램 (이 기사의 소유자이므로)과 기사 콘텐츠를 업데이트 할 수있는 기사 "편집자"를 추가 할 수있는 위치를 가정 해 보겠습니다.

class User 
    include Mongoid::Document 
    has_many :articles # as owner of the articles 
    has_and_belongs_to_many :articles # as editor of the articles 
end 

class Article 
    include Mongoid::Document 
    belongs_to :user 
    has_and_belongs_to_many :editors, :class_name => 'User' 
end 

내가 알고 싶은 것은 내 사용자 모델에서 기사 연결을 호출해야하는 방법입니다. 내 기사에는 저자와 편집자가 있습니다.이 저자는 저에게 강력한 명명 규칙으로 보이지만 사용자는 그가 만든 기사를 가지고 있으며 기사는 편집자입니다. 마지막 두 단체를 어떻게 부르겠습니까/이름을 밝히고 선언합니까?

답변

3

나는 이것을 :edited_articles:authored_articles 또는 :owned_articles 또는 이와 유사한 이름으로 부릅니다. 그냥 :class_name:foreign_key 또는 :through 한정자를 추가하는 것을 잊지 마십시오.

업데이트 : 당신이 디폴트로 연결 테이블을 필요 has_and_belongs_to_many 관계를 들어

이 두 조인 된 테이블의 이름. 예 : 귀하의 경우 articles_users. 이 표에는 적절하게 두 개의 ID, user_idarticle_id이 있습니다. 이렇게하면 레일이 자동으로 모델을 연결합니다. 물론

has_and_belongs_to_many :editors, :class_name => 'User', :foreign_id => 'user_id' 

은 조인 테이블에 editor_id를 호출하는 경우 그 다음을 사용합니다. 그리고 사용자 측에서 반대도 마찬가지입니다.

+1

'has_and_belongs_to_many : edited_articles, : class_name =>'기사 '와 같은 : foreign_key =>'editor_id '? –

관련 문제