0
ingredient.rb:的Rails 3:如何使在MySQL超過3個表(附:通過模型)聯接
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?
感謝您的幫助!
OMG ......我沒有看到!非常感謝您的幫助! –
將模型更改爲「has_many:ingredient_with_quantities」並將查詢改爲: Recipe.find(:all,:include => {:ingredient_with_quantities =>:ingredient},:conditions =>「ingredients.name ='ingredient1'」) –
它能解決你的問題嗎?你使用導軌2或3嗎? –