Rails ActiveRecord关系 - 有许多属于关联

jku*_*ner 4 ruby-on-rails table-relationships models many-to-one

我创建了3个模型:

  • 文章:包含一篇文章
  • 标签:包含标签
  • ArticleTag:用于将多对一标签与文章关系相关联.它包含tag_id和article_id.

我遇到的问题是我对主动记录技术还不熟悉,我不明白定义所有内容的正确方法.目前,我认为这是错误的,我有一个

ArticleTag
 belongs_to :article
 belongs_to :tag
Run Code Online (Sandbox Code Playgroud)

现在,从这里开始我的想法就是添加

  Article
   :has_many :tag
Run Code Online (Sandbox Code Playgroud)

我不确定我是否正确接近这一点.谢谢您的帮助!

Joh*_*ley 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
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)


Joh*_*lla 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.)
Run Code Online (Sandbox Code Playgroud)