ActiveRecord, how to add an existing record to an association in has_many: through relationships in rails?

In my rails project, I have three models:

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

With this simple has_many: through customization, how can I take this recipe, for example:

@recipe = Recipe.first

and add a category to this recipe based on an existing category, and update it also in the corresponding category.

So:

@category = #Existing category here
@recipe.categories.build(@category)

and then

@category.recipes

will contain @recipe?

The reason I ask about this is because I try to achieve this behavior through gem rails_admin, and every time I create a new recipe object, the form for specifying its categories is a form for creating a new category, and how to attach existing to this recipe.

, ActiveRecord many_to_many.

.

+4
1

build new, .

category @recipe.categories, :

@recipe.categories << @category

RecipeCategorization ( ).

@category.recipes @recipe

+9

All Articles