如何在Rails的ActiveRecord的正确分配的has_many / belongs_to的关系? [英] How to assign a has_many/belongs_to relation properly in Rails ActiveRecord?

查看:178
本文介绍了如何在Rails的ActiveRecord的正确分配的has_many / belongs_to的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文章和作者的模型一个Rails应用程序。如果我有一个作家和一个职位,想表明,作者应该是文章的所有者,或该物品属于作者,有什么北京时间这样做的最佳做法是什么?特别是:

I have a rails app with articles and author model. If I have an author and a post and want to indicate that the author should be the owner of the article, or that the article belongs to the author, what ist the best practice to do so? In particular:

这是否有所作为,如果我设置

Does it make a difference if I set

my_article.author_id = author_one.id

或者如果我这样做

or If I do

author_one << my_article

所使用的关联是

  • 作者的has_many文章
  • 文章belongs_to的作者

和,顺便说一句,这将是看它了,如果类似的问题出现的最好方法是什么?

And, by the way, what would be the best way to look it up if similar questions appear?

推荐答案

没有跟随3之间的区别:

There is not difference between the 3 following:

my_article.author_id = author_one.id
my_article.save
# same as
my_article.author = author_one
my_article.save
# same as
author_one.articles << my_article

要设置一个特定帖子的主人,是最常见的和可读性的方法是:

To set the owner of a particular post, the most common and readable way would be:

post.author = author
post.save

短版

post.update_attributes(author_id: author.id) # call an implicit save

这篇关于如何在Rails的ActiveRecord的正确分配的has_many / belongs_to的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆