簡體   English   中英

Rails 3:如何通過3個表在mysql中進行連接(在模型中使用:through)

[英]Rails 3: How to make a join in mysql over 3 tables (with :through in the model)

ingredient.rb:

class Ingredient < ActiveRecord::Base
  has_many :recipes, :through => :ingredients_with_quantities
  has_many :ingredients_with_quantities

ingredient_with_quantity.rb:

class IngredientWithQuantity < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient

recipe.rb:

class Recipe < ActiveRecord::Base
  has_many :ingredients, :through => :ingredients_with_quantities
  has_many :ingredients_with_quantities

我想做一個查詢,獲取包含特定成分名稱的所有食譜。

試過這個查詢:

Recipe.find(:all, :include => {:ingredients_with_quantities => :ingredients}, :conditions => "ingredients.name = 'ingredient1'")

但我得到這個錯誤:

NameError: uninitialized constant Recipe::IngredientsWithQuantity

有人能告訴我查詢有什么問題嗎?

我可以在SQL中使用以下命令進行成功查詢:

SELECT r . * FROM recipes r, ingredient_with_quantities iq, ingredients i 
WHERE i.name =  "ingredient1"
AND iq.recipe_id = r.id 
AND iq.ingredient_id = i.id

如何使用ActiveRecord在Rails中查找此查詢?

謝謝你的協助!!

它是:ingredient_with_quantities而不是:ingredients_with_quantities (你在ingredient之后加上“s”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM