Hi all,
I have a rather weird problem. Three models in has_many :through
relationship:
Nutrient <-- IngredientsNutrient --> Ingredient
Nutrient has_many :ingredient_nutrients
Nutrient has_many Ingredients, :through => :ingredient_nutrients
Ingredient has_many :ingredient_nutrients
Ingredient has_many :nutrients, :through => :ingredient_nutrients
IngredientsNutrient belongs_to :nutrient
IngredientsNutrient belongs_to :ingredient
IngredientsNutrient is a model, because I need to specify the quantity
of nutrients per ingredient.
With this, I wanted to create a form for Ingredient model which
includes IngredientsNutrient fields for each Nutrient.all.
I’ve added to Ingredient:
accepts_nested_attributes_for :ingredients_nutrient
and went on to add in the view:
<% f.fields_for :ingredients_nutrient do |in_f| %>
....
<% end %>
In the controller, I have the following code:
for nutrient in Nutrient.all
@ingredient.ingredients_nutrients.build({ :nutrient_id =>
nutrient.id })
end
When I submit the form filling out all the fields, it fails validation
saying that ingredient_id cannot be blank (exact message is:
“Ingredient nutrients ingredient can’t be blank”).
My initial assumption was that the ingredient_id needs not be
specified, but either Rails doesn’t think so, or I have made an error
in coding. I’ve double checked Ryan’s examples of nested attributes,
but I can’t see anything. The only thing I’ve noticed that he didn’t
deal with has_many-through type of relationship.
Can anyone please point me in the right direction?
Thanks,
–
Branko