在我的 Rails 项目中,我有三个模型:
class Recipe < ActiveRecord::Base
has_many :recipe_categorizations
has_many :category, :through => :recipe_categorizations
accepts_nested_attributes_for :recipe_categories, allow_destroy: :true
end
class Category < ActiveRecord::Base
has_many :recipe_categorizations
has_many :recipes, :through => :recipe_categorizations
end
class RecipeCategorization < ActiveRecord::Base
belongs_to :recipe
belongs_to :category
end
通过这个简单的 has_many :through 设置,我怎样才能像这样获取给定的食谱:
@recipe = Recipe.first
并根据现有类别向此食谱添加类别,并在相应类别上对其进行更新。
所以:
@category = #Existing category here
@recipe.categories.build(@category)
然后
@category.recipes
将包含@recipe?
我问这个的原因是因为我试图通过 gem rails_admin 实现这种行为,每次我创建一个新的食谱对象时,指定它的类别的表单就是创建一个新类别的表单,而不是而不是将现有的附加到此食谱。
因此,了解 ActiveRecord 如何以多对多关系将现有记录关联到新创建的记录会很有帮助。
谢谢。
最佳答案
build方法与 new
方法足够接近,用于创建新记录。
如果您需要将当前的类别
添加到@recipe.categories
,您只需:
@recipe.categories << @category
这将在 RecipeCategorization
表中添加一条记录(自动保存)。
现在 @category.recipes
将包含 @recipe
关于ruby-on-rails - ActiveRecord 如何将现有记录添加到 has_many :through relationship in rails? 中的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665494/