Rails:添加新的 has_and_belongs_to_many 关联而不创建对象?
是否可以简单地添加新关联?
我有两个对象通过 has_and_belongs_to_many 连接在一起。 模型 A 始终是唯一的,但相应的模型 B 对象可能已在数据库中。
当创建模型A时,我如何告诉Rails找到相应的模型B对象并将两个模型绑定在一起 - 或者 - 如果没有适当的模型B strong> 对象不存在然后继续创建它吗? 我应该执行 .where 查找,然后执行 SQL 查询以将两个 ID 添加到联接表中,还是有一个本机 ActiveRecord 方法可以执行此操作?
Is it possible to simply add new associations?
I have two objects tied together via has_and_belongs_to_many. Model A will always be unique but corresponding Model B objects might already be in the database.
When Model A is created how do I tell Rails to find corresponding Model B objects and tie the two models together - or - if no the appropriate Model B object does not exist then go ahead and create it?
Should I do a .where lookup and then a SQL query to add the two IDs to the join table, or is there a native ActiveRecord method for doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rails 关联不以受限制的方式绑定模型。假设您有一个 User 和一个 Post 模型。关联 User has_many Posts 只是创建一个接口。使用该界面,您现在可以执行 :
操作,这将返回用户的所有帖子。如果您想添加或查找帖子,可以执行:
这将查找帖子或创建帖子。
另外,在您的示例中,您提到了一对多关联。因此,您不需要具有并属于许多关联,而是需要 has_many/belongs_to one。
A Rails association does not tie models in a restricted manner. Suppose that you have a User and a Post model. The association User has_many Posts simply creates an interface. Using that interface, you can now do :
and this will return all the posts of the user. If you want to add or find a post, you can execute :
This will either find the post or create it.
Also, in your example, you mention a one to many association. Thus you do not need a has and belongs to many association, but a has_many/belongs_to one.