class Recipe < ActiveRecord::Base
has_many :ingredients_recipes
has_many :ingredients, :through => :ingredients_recipes
after_save :add_ingredients
attr_writer :ingredient_ids
private
def add_ingredients
if @ingredient_ids
ingredients_recipes.destroy_all
@ingredient_ids.each do |ingredient_id|
ingredient = Ingredient.find(ingredient_id)
ingredients << ingredient if ingredient
end
end
end
end
Is this the best way to go about this, or is there a better way that
I've missed? It seems like there would be a built-in feature for this
or a plugin out there. Or at least a best practice. I do like this
approach for its ease of testing (I would much rather test models than
controllers).
Thanks,
Bryan
def add_ingredients
ingredients_recipes.destroy_all
ingredients << Ingredient.find(@ingredient_ids)
end
I think using << works -- in looking at the source for
ActiveRecord::Associations::AssociationCollection (in 1.2.x), the <<
method has the following code and comments:
# Add +records+ to this association. Returns +self+ so method
calls may be chained.
# Since << flattens its argument list and inserts each record,
+push+ and +concat+ behave identically.
def <<(*records)
-Sam
class Ingredient < ActiveRecord::Base
has_many :uses
has_many :recipes, :through => :uses
end
It doesn't read quite as well from the Recipe side, but it's much
easier to type. (=
-Sam