2
我正在使用三个表实现视图,其中一个表连接表。下面是表:在belongs_to模型中使用委托时出现'未初始化常量'错误
方药:
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
这似乎是工作正常,当我创建一个新的配方 - 我可以编辑食谱线,一切运行顺利。 当我创建一个视图来显示来自成分表的成分名称的食谱时,我在连接表中创建了一个委托。然而,当我尝试使用视图中的委托:
<% @recipe.ingredients_recipes.each do |r| %>
<%= r.ingredient_id %> <br>
<%= r.name %>
<% end %>
我得到以下错误:
uninitialized constant IngredientsRecipe::Ingredients
当我删除它在运行时错误<%= r.name%>行。我是错误地定义委托还是可能造成这种情况?
+1为单数/复数提示...这也呈现':foreign_key'的用法无用。 – hurikhan77 2010-09-26 22:40:18
这样做 - 非常感谢你。 关于类名,我通过脚手架做到了,因为它是一个连接表,所以我不得不使用复数表中的两个表名和第二个单词自动从条目复数中剥离出来,因此成为了IngredientsRecipe。 – gugguson 2010-09-27 13:09:41