Ruby on rails ActiveRecord如何通过rails中的关系将现有记录添加到has_many中的关联中?

Ruby on rails ActiveRecord如何通过rails中的关系将现有记录添加到has_many中的关联中?,ruby-on-rails,ruby,activerecord,many-to-many,rails-admin,Ruby On Rails,Ruby,Activerecord,Many To Many,Rails Admin,在我的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 <

在我的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
并根据现有类别向该配方添加一个类别,并在相应类别上进行更新

因此:

然后

@category.recipes
将包含@recipe

我问这个问题的原因是因为我试图通过gem rails_admin实现这一行为,每次我创建一个新的配方对象时,指定其类别的表单就是创建一个新类别的表单,而不是将一个现有类别附加到此配方

因此,了解ActiveRecord如何将现有记录与多对多关系中新创建的记录相关联会很有帮助

谢谢。

该方法与用于创建新记录的
新方法非常接近

如果需要将当前的
类别添加到
@recipe.categories
,只需:

@recipe.categories << @category

@recipe.categories谢谢!我不是在@AdamBronfin上查看的,不是真的。电铲操作员不再在轨道5中工作。
@category.recipes
@recipe.categories << @category