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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With