Rails ActiveRecord 关系 - 有很多且属于关联
我创建了 3 个模型:
- 文章:包含一篇文章
- 标签:包含标签
- ArticleTag:用于将多对一标签与文章关系关联起来。它包含一个tag_id 和一个article_id。
我遇到的问题是我对活动记录技术相当陌生,我不明白定义一切的正确方法。目前,我认为这是错误的,我有一个
ArticleTag
belongs_to :article
belongs_to :tag
“现在”,从这里我的想法是然后添加
Article
:has_many :tag
我不确定我是否正确地处理了这个问题。感谢您的帮助!
I've created 3 models:
- Article: contains an article
- Tag: contains tags
- ArticleTag: meant for associating a many-to-one tags to article relationship. It contains a tag_id and an article_id.
The problem I'm having is I'm fairly new to the active record technology and I don't understand the proper way to define everything. Currently, which I think is wrong, is I have a
ArticleTag
belongs_to :article
belongs_to :tag
Now, from here my thought was to then add
Article
:has_many :tag
I'm not sure if im approaching this correctly at all. Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于您是否想要连接模型。连接模型允许您针对两个其他模型之间的关联保存额外的信息。例如,也许您想记录文章被标记的时间戳。该信息将根据连接模型进行记录。
如果您不需要连接模型,则可以使用简单的
has_and_belongs_to_many
关联:使用
Tagging
连接模型(这是一个比ArticleTag< 更好的名称) /code>),它看起来像这样:
It depends whether you want a join model or not. A join model lets you hold extra information against the association between two other models. For example, perhaps you want to record a timestamp of when the article was tagged. That information would be recorded against the join model.
If you don't want a join model, then you could use a simple
has_and_belongs_to_many
association:With a
Tagging
join model (which is a better name thanArticleTag
), it would look like this:当关系是单向时,您应该使用
has_many
。一篇文章有很多标签,但标签也有很多文章,所以这不太正确。更好的选择可能是has_and_belongs_to_many
:一篇文章有许多标签,并且这些标签也引用文章。Abelongs_toB
表示A引用B;A has_one B
表示 B 引用 A。以下是您可能会看到的关系的摘要:
You should use
has_many
when the relationship is one-way. An article has many tags, but tags also have many articles, so that's not quite right. A better choice might behas_and_belongs_to_many
: an Article has many Tags, and those Tags also reference articles.A belongs_to B
means that A references B;A has_one B
means that B references A.Here's a summary of the relationships you might see:
在我的脑海中,文章应该是:
Off the top of my head, Article should be: