I am trying to implement a many to many relation using a model in rails 3 for my demo app.
It all worked fine untill I tried to add a model that will hold a bit more data on the relation.
I have a recipe, ingredient, Ingredient_Recipe models
File:ingredient_recipe.rb
class IngredientRecipe < ActiveRecord::Base
attr_accessible :created_at, :ingredient_id, :order, :recipe_id
belongs_to :recipes
belongs_to :ingredients
end
File:ingredient.rb
class Ingredient < ActiveRecord::Base
has_many :ingredientRecipe
has_many :recipes, :through => :ingredientRecipe
...
File:recipes.rb
class Recipe < ActiveRecord::Base
has_many :ingredientRecipe
has_many :ingredients, :through => :ingredientRecipe
...
in the ui
<td >
<% @recipe.ingredients.each do |ingredient| %>
ingredient.name
<% end %>
</td >
table
ingredient_id, recipe_id, order, created_at, updated_at
Now, this doesnt work so well…
oh well , and a good resource for implementing many to many would be very apprecieated
I see a few errors in the model code. It is hard to say exactly what those might do.
Your recipes model should look like this:
Your ingredient model should look like this
Associations should be underscored and lower-cased,
has_manyrelationships should be pluralized.You said
Ingredient_Recipecontains, the content is good but it should be namedingredient_recipe.rband the class name should beIngredientRecipeunsure if that was just my misunderstanding.The first error you are experiencing said undefined method
recipe_ingredient, which would make sense, the association name isingredient_recipes, the through parameter takes the exact name of the association.the second issue is hard to say, but I would make the above modifications first and see if that improves the situation.
the third item, I would say no. Follow the railscast’s instructions.
The railscast in question is a good resource, I have used that specific one before.
EDIT, just noticed the belongs_to is incorrect as well.
within the
IncredientRecipeclassa
belongs_toassociation should be singular.