我有以下结构:
数据库:
create_table :recipes do |t|
t.string :name
t.string :categoryname
end
create_table :ingredients do |t|
t.string :name
t.string :categoryname
t.string :defaultunit
t.integer :price
end
create_table :recipeingredients do |t|
t.integer :recipe_id
t.integer :ingredient_id
t.integer :quantity
t.string :unit
end
楷模:
class Ingredient < ActiveRecord::Base
has_many :recipeingredients
has_many :recipes, :through=>:recipeingredients
end
class Recipe < ActiveRecord::Base
has_many :recipeingredients
has_many :ingredients, :through => :recipeingredients
end
class Recipeingredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
irb(main):337:0* r=Recipe.find(1)
Recipe Load (0.5ms) SELECT "recipes".* FROM "recipes" WHERE "recipes"."id" = ? LIMIT 1 [["id", 1]]
=> #<Recipe id: 1, name: "Tiramisu", categoryname: "édesség", created_at: "2013-02-26 09:31:55", updated_at: "2013-02-26 09:
31:55">
irb(main):338:0> r.ingredients
Ingredient Load (0.5ms) SELECT "ingredients".* FROM "ingredients" INNER JOIN "recipeingredients" ON "ingredients"."id" = "recipeingredients"."ingredient_id" WHERE "recipeingredients"."recipe_id" = 1
=> [#<Ingredient id: 1, name: "mascarpone", categoryname: "tejtermék", defaultunit: "gr", price: 500, created_at: "2013-02-26 09:32:21", updated_at: "2013-02-26 09:32:21">]
我想要实现的是能够在 r.ingredients 中访问 recipeingredients.quantity 和 recipeingredients.unit。
我相信它可以通过以某种方式更改查询来实现,以便它返回类似SELECT * FROM "ingredients" INNER JOIN...
我的目标是能够在视图中使用一个循环列出成分的数量和属性。
有没有办法做到这一点?到目前为止,我在论坛上找到的任何东西都没有起作用。