ActiveRecord how to add existing record to association in has_many :through relationship in rails?
Asked Answered
A

1

6

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 setup, how can I take a given recipe like so:

@recipe = Recipe.first

and add a category to this recipe based off an existing category, and have it be updated on the respective category as well.

So:

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

and then

@category.recipes

will contain @recipe?

The reason why I ask this is because I'm trying to achieve this behavior through the gem rails_admin, and every time I create a new recipe object, the form to specify it's categories is the form to create a new category, rather than attach an existing one to this recipe.

So it would be helpful to understand how ActiveRecord associates existing records to newly created records in a many_to_many relationship.

Thanks.

Anaximander answered 31/10, 2014 at 0:3 Comment(0)
C
13

The build method is close enough to the new method, used to create new records.

if you need to add a current category to @recipe.categories, you just need to:

@recipe.categories << @category

This will add a record in the RecipeCategorization table (automatically saving it).

now @category.recipes will include @recipe

Coltin answered 31/10, 2014 at 0:18 Comment(4)
Thanks! Isnt << the bitshift operator?Anaximander
Check it out has_manyColtin
@AdamBronfin not really. https://mcmap.net/q/193890/-what-does-lt-lt-mean-in-rubyEductive
The shovel operator no longer works in Rails 5. github.com/rails/rails/issues/25906Detestation

© 2022 - 2024 — McMap. All rights reserved.