2
votes

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,

1

1 Answers

2
votes

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: