2009-12-15 77 views
4

我创建了3种型号协会:Rails的ActiveRecord的关系 - 有许多属于

  • 文章:有一篇文章
  • 标签:包含标签
  • ArticleTag:意味着一个多到关联文章关系中的一个标签。它包含一个tag_id和一个article_id。

我遇到的问题是我对活动记录技术相当陌生,我不明白定义一切的正确方法。目前,我认为这是错误的,是我有一个

ArticleTag 
belongs_to :article 
belongs_to :tag 

现在,从这里开始我的想法是,再加入

Article 
    :has_many :tag 

我不确定是不是我处理这个正确的。谢谢您的帮助!

回答

10

这取决于你是否想要一个连接模型或不。连接模型允许您针对两个其他模型之间的关联持有额外的信息。例如,也许你想记录文章标记时间的时间戳。该信息将根据加入模型进行记录。

如果你不想加入的模式,那么你可以使用一个简单的has_and_belongs_to_many协会:

class Article < ActiveRecord::Base 
    has_and_belongs_to_many :tags 
end 

class Tag < ActiveRecord::Base 
    has_and_belongs_to_many :articles 
end 

随着Tagging连接模型(这是比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选项非常适合将user_id放入标记中。 – MattMcKnight 2009-12-15 15:39:15

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

为什么这个社区wiki? – 2009-12-15 15:04:13