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.