Rails 3 ActiveRecord 关联

发布于 2024-12-11 18:34:39 字数 1024 浏览 3 评论 0原文

我将这 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

豆芽 2024-12-18 18:34:39

没有要验证的模型,但我突然想到,你需要告诉它你没有加入原始模型

Recipe.joins(:ingredients).joins(:ingredients => :stocks).select:

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

Recipe.joins(:ingredients).joins(:ingredients => :stocks).select:
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文