Rails:添加新的has_and_belongs_to_many关联而不创建对象?

时间:2011-04-10 22:24:29

标签: ruby-on-rails rails-activerecord has-and-belongs-to-many

是否可以简单地添加新关联?

我有两个对象通过has_and_belongs_to_many连接在一起。 模型A 始终是唯一的,但相应的模型B 对象可能已存在于数据库中。

当创建模型A 时,如何告诉Rails找到相应的模型B 对象并将两个模型绑定在一起 - 或 - 如果没有合适的模型B 对象不存在然后继续创建它? 我应该执行.where查找,然后使用SQL查询将两个ID添加到连接表中,还是有一个本机ActiveRecord方法来执行此操作?

2 个答案:

答案 0 :(得分:2)

# the piece from create action of ProductsController
categories = Array.new(@product.categories)
@product.categories.clear
categories.each do |c|
  @product.categories << Category.find_or_create_by_name(c.name)
end
# ready to @product.save

答案 1 :(得分:1)

Rails关联不会以受限制的方式绑定模型。假设您有一个User和Post模型。关联User has_many Posts只是创建一个界面。使用该界面,您现在可以:

user.posts

这将返回用户的所有帖子。如果要添加或查找帖子,可以执行:

Post.find_or_create_by_user_id(...)

这将找到帖子或创建它。

此外,在您的示例中,您提到了一对多关联。因此,您不需要has并且属于许多关联,但是has_many / belongs_to one。