在模型中的belongs_to中使用委托时,获取“未初始化的常量”错误

时间:2010-09-26 14:38:52

标签: ruby-on-rails

我正在一个带有三个表的模型上实现一个视图,其中一个表是连接表。以下是表格:

配方:

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

成分:

class Ingredient < ActiveRecord::Base
  # has_and_belongs_to_many :recipes

  has_many :ingredients_recipes
  has_many :recipes, :through => :ingredients_recipes

end

他们之间的联接表:

class IngredientsRecipe < ActiveRecord::Base
  belongs_to :recipes
  belongs_to :ingredients, :foreign_key => "ingredient_id"

  delegate :name, :to => :ingredients

end

这似乎工作正常,当我创建一个新配方 - 我可以编辑配方行,一切运行顺利。 当我创建一个视图以使用Ingredients表中的成分名称显示配方时,我在连接表中创建了一个委托。但是,当我尝试在视图中使用委托时:

  <% @recipe.ingredients_recipes.each do |r| %>
    <%= r.ingredient_id %> <br>  
    <%= r.name %>
  <% end %>

我收到以下错误:

uninitialized constant IngredientsRecipe::Ingredients

当我删除&lt;%= r.name%&gt;它运行没有错误。我是否错误地定义了代表或者导致了什么?

1 个答案:

答案 0 :(得分:3)

我相信IngredientsRecipes中的belongs_to关联应该是单数,而不是复数,例如:

class IngredientsRecipe < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient, :foreign_key => "ingredient_id"

  delegate :name, :to => :ingredient

end

另外,请检查您的班级名称。它应该都是单数(IngredientRecipe),或全部复数(IngredientsRecipes)......我不确定哪个,但我知道它不应该混合。

最后,为什么使用连接模型?如果您在IngredientsRecipes中没有任何其他属性,只需像注释掉的那样使用HABTM。