【发布时间】:2012-05-28 18:28:10
【问题描述】:
我正在尝试为我的类创建一个 has_many :through 关系,但对如何实际实现相关数据的保存和检索感到困惑。
我有一个食谱类、成分类和数量类,它们是关联的 :through。这是我现在的课程:
#models/recipe.rb
class Recipe < ActiveRecord::Base
has_many :amounts
has_many :ingredients, :through => :amounts
end
#models/ingredient.rb
class Ingredient < ActiveRecord::Base
has_many :amounts
has_many :recipes, :through => :amounts
end
#models/amounts.rb
class Amounts < ActiveRecord::Base
belongs_to :recipes
belongs_to :ingredients
end
此外,这里是一个链接,指向创建食谱的基本形式的要点:https://gist.github.com/2820455
以及创建代码本身的要点: https://gist.github.com/2820294
当我提交表单时,我收到此错误:
uninitialized constant Recipe::Amount
还有这个应用程序跟踪:
app/controllers/recipes_controller.rb:57:in 'block in create'
app/controllers/recipes_controller.rb:56:in 'create'
我对 Ruby on Rails 非常陌生,实现这种关系并将 Amounts 值插入到表中让我难以置信......!
【问题讨论】:
-
为什么你有 has_and_belongs_to_many :recipes in ingredients.rb?
-
哎呀。那是我旧实现的残余。现在删除它。
-
您遇到错误的要点是什么?
-
在要点中它将是第 23 行。作为@recipe.save 调用
-
belongs_to 在您的 amount.rb 文件中必须是单数,例如:- 它将是 belongs_to :recipe 和 belongs_to :ingredient
标签: ruby-on-rails ruby-on-rails-3 associations has-many-through