Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord how to add existing record to association in has_many :through relationship 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 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.

like image 363
Adam Bronfin Avatar asked Oct 31 '14 00:10

Adam Bronfin


1 Answers

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

like image 173
mohameddiaa27 Avatar answered Nov 14 '22 02:11

mohameddiaa27