Rails 3 ActiveRecord 关联
我将这 4 个模型通过 has_many、belongs_to 关联相互连接。基本的有 2 个(配方、成分)。另外两个存储基于前两个的附加信息。
class Recipe
has_many :ingredients, :through => :prescriptions
has_many :prescriptions
end
class Ingredient
has_many :recipes, :through => :prescriptions
has_many :prescriptions
has_many :stocks
end
class Stock
belongs_to :ingredient
end
class Prescription
belongs_to :recipe
belongs_to :ingredient
end
我尝试获取可用库存的食谱,即 Recipe.joins(:ingredients).joins(:stocks) 但是,我收到错误:
ActiveRecord::ConfigurationError: Association named 'stock' was not found; perhaps you misspelled it?
我尝试达到的 SQL 查询是:
SELECT "recipes".* FROM "recipes"
INNER JOIN "prescriptions"
ON "prescriptions"."recipe_id" = "recipes"."id"
INNER JOIN "ingredients"
ON "ingredients"."id" = "prescriptions"."ingredient_id"
---
INNER JOIN "stocks"
ON "stocks"."ingredient_id" = "ingredients"."id"
---
最后一个“INNER JOIN”是我无法在 Rails 3 代码中解释。有什么想法吗?
谢谢你,
I have these 4 models connected with each other through has_many, belongs_to associations. The basic are 2 (Recipe, Ingredient). The other 2 store additional information based on previous two.
class Recipe
has_many :ingredients, :through => :prescriptions
has_many :prescriptions
end
class Ingredient
has_many :recipes, :through => :prescriptions
has_many :prescriptions
has_many :stocks
end
class Stock
belongs_to :ingredient
end
class Prescription
belongs_to :recipe
belongs_to :ingredient
end
I try to fetch Recipes which are available stock, that is Recipe.joins(:ingredients).joins(:stocks) but, I get an error:
ActiveRecord::ConfigurationError: Association named 'stock' was not found; perhaps you misspelled it?
The SQL query I try to reach is:
SELECT "recipes".* FROM "recipes"
INNER JOIN "prescriptions"
ON "prescriptions"."recipe_id" = "recipes"."id"
INNER JOIN "ingredients"
ON "ingredients"."id" = "prescriptions"."ingredient_id"
---
INNER JOIN "stocks"
ON "stocks"."ingredient_id" = "ingredients"."id"
---
the last "INNER JOIN" is that I cannot interpret in rails 3 code. Any Ideas?
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有要验证的模型,但我突然想到,你需要告诉它你没有加入原始模型
Don't have a model to verify, but off the top of my head, you need to tell it that you're not joining off the original model