Reputation: 819
I'm implementing a view on a model with three tables, one of them join table. Here are the tables:
Recipe:
class Recipe < ActiveRecord::Base
# validates :name, :presence => true
# validates :directions, :presence => true
# has_and_belongs_to_many :ingradients
has_many :ingredients_recipes
has_many :ingredients, :through => :ingredients_recipes
accepts_nested_attributes_for :ingredients_recipes, :allow_destroy => true
end
Ingredient:
class Ingredient < ActiveRecord::Base
# has_and_belongs_to_many :recipes
has_many :ingredients_recipes
has_many :recipes, :through => :ingredients_recipes
end
And the join table between them:
class IngredientsRecipe < ActiveRecord::Base
belongs_to :recipes
belongs_to :ingredients, :foreign_key => "ingredient_id"
delegate :name, :to => :ingredients
end
This seems to work ok, when I create a new recipe - I can edit the recipe lines and everything runs smoothly. When I create a view to show the Recipe with the Ingredient name from Ingredients table I created a delegate in the join table. However when I try to use the delegate within the view:
<% @recipe.ingredients_recipes.each do |r| %>
<%= r.ingredient_id %> <br>
<%= r.name %>
<% end %>
I get the following error:
uninitialized constant IngredientsRecipe::Ingredients
When I remove the <%= r.name %> line it runs without errors. Am I defining the delegate wrongly or what could be causing this?
Upvotes: 2
Views: 4500
Reputation: 86
I believe your belongs_to associations in IngredientsRecipes should be singular, not plural, eg:
class IngredientsRecipe < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient, :foreign_key => "ingredient_id"
delegate :name, :to => :ingredient
end
Also, check the case of your class name. It should either be all singular (IngredientRecipe), or all plural (IngredientsRecipes) ... I'm not sure which, but I know it shouldn't be mixed.
Finally, why are you using a join model? If you don't have any other attributes in IngredientsRecipes, just use HABTM like your commented out lines.
Upvotes: 3