在我的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:通过设置,我怎么能像这样给定配方:
@recipe = Recipe.first
并根据现有类别在此食谱中添加一个类别,并在相应的类别上对其进行更新。
所以:
@category = #Existing category here
@recipe.categories.build(@category)
进而
@category.recipes
会包含@recipe吗?
之所以这样问,是因为我试图通过gem rails_admin实现此行为,并且每次创建新配方对象时,用于指定其类别的表单就是创建新类别的表单,而不是附加一个现有的这个食谱。
因此,了解ActiveRecord如何以many_to_many关系将现有记录与新创建的记录相关联将很有帮助。
谢谢。
最佳答案
build方法与用于创建新记录的new
方法足够接近。
如果您需要将当前category
添加到@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/