私は次の構造を持っています:
データベース:
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...
私の目標は、ビューでサイクルの 1 つを使用して、成分の量と特性を一覧表示できるようにすることです。
それを行う方法はありますか?これまでのところ、フォーラムで見つけたものは何も機能しませんでした.