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

Ada*_*fin 5 ruby activerecord many-to-many ruby-on-rails 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 < ActiveRecord::Base
  has_many :recipe_categorizations
  has_many :recipes, :through => :recipe_categorizations
end

class RecipeCategorization < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :category
end
Run Code Online (Sandbox Code Playgroud)

有了这个简单的has_many:通过设置,我该如何处理给定的食谱:

@recipe = Recipe.first
Run Code Online (Sandbox Code Playgroud)

并根据现有类别向此配方添加类别,并在相应类别上更新.

所以:

@category = #Existing category here
@recipe.categories.build(@category)
Run Code Online (Sandbox Code Playgroud)

然后

@category.recipes
Run Code Online (Sandbox Code Playgroud)

将包含@recipe?

为什么我问这个是因为我想要实现通过创业板rails_admin这种行为,我每次创建新配方的对象,形式,将其指定的类别的原因是为了创建一个新的类别,而不是附加的形式现有的一个配方.

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

谢谢.

moh*_*a27 12

构建方法是足够接近的new方法,用来创造新的纪录.

如果你需要一个电流添加category@recipe.categories,你只需要:

@recipe.categories << @category
Run Code Online (Sandbox Code Playgroud)

这将在RecipeCategorization表格中添加一条记录(自动保存).

现在@category.recipes将包括@recipe