2009-12-15 4 views
4

협회에 속한다 :레일 액티브 관계 - 많은이 있고 나는 3 개 모델을 만든

  • 기사 : 기사에게
  • 태그를 포함는 : 태그를
  • ArticleTag이 포함되어 많은-A를 연결에 대한 의미 문서 관계에 대한 태그. 여기에는 tag_id 및 article_id가 포함됩니다.

나는 현재 활성 레코드 기술에 대해 새삼스럽고 모든 것을 정의하는 올바른 방법을 이해하지 못한다는 문제가 있습니다. 현재, 내가 잘못 생각하는, 내가 여기에서 내 생각은 다음 메신저 전혀 올바르게 접근하는 경우

Article 
    :has_many :tag 

잘 모르겠어요 추가했다, 이제

ArticleTag 
belongs_to :article 
belongs_to :tag 

을 가지고있다. 도와 주셔서 감사합니다!

답변

10

그것은 당신 여부 따라 달라집니다 조인 모델을 원하십니까? 조인 모델을 사용하면 다른 두 모델 간의 연관성에 대한 추가 정보를 보유 할 수 있습니다. 예를 들어 기사에 태그가 추가 된 시간 소인을 기록하려고합니다. 이 정보는 조인 모델에 대해 기록됩니다.

당신이 가입 모델을 원하지 않는 경우, 당신은 간단한 has_and_belongs_to_many 협회 사용할 수 있습니다하십시오 Tagging

class Article < ActiveRecord::Base 
    has_and_belongs_to_many :tags 
end 

class Tag < ActiveRecord::Base 
    has_and_belongs_to_many :articles 
end 

이 (ArticleTag보다 더 좋은 이름 인) 모델을 조인, 그것은 다음과 같을 것 :

class Article < ActiveRecord::Base 
    has_many :taggings 
    has_many :tags, :through => :taggings 
end 

class Tag < ActiveRecord::Base 
    has_many :taggings 
    has_many :articles, :through => :taggings 
end 

class Tagging < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :tag 
end 
+0

has_many : through 옵션은 tagging에도 user_id를 넣기에 좋습니다. – MattMcKnight

5

관계가 단방향이면 has_many을 사용해야합니다. 기사에는 많은 태그가 있지만 태그에도 기사가 많으므로 적절치 않습니다. 더 나은 선택은 has_and_belongs_to_many 일 수 있습니다 : 기사에는 많은 태그가 있고 그 태그는 또한 기사를 참조합니다. A belongs_to B은 A가 B를 참조 함을 의미합니다. A has_one B가 B를 참조하는 A. 여기

는 당신이 볼 수있는 관계를 요약 한 것을 의미 :

Article 
    has_and_belongs_to_many :tags # An article has many tags, and those tags are on 
            # many articles. 

    has_one     :author # An article has one author. 

    has_many    :images # Images only belong to one article. 

    belongs_to    :blog # This article belongs to one blog. (We don't know 
            # just from looking at this if a blog also has 
            # one article or many.) 
0

내 머리 위로 끄기 제는해야한다 :

has_many :article_tags 
has_many :tags, :through => :article_tags 
+0

왜 커뮤니티 위키입니까 ?? –