繁体   English   中英

栏杆3,包括联合表中的字段

[英]rails 3 including fields from joint table

我有以下结构:

数据库:

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...

我的目标是能够在视图中使用一个循环列出成分的数量和属性。

有办法吗? 到目前为止,我在论坛上发现的任何内容均无济于事。

取决于您是偶尔还是始终要,即每次装入配方时始终装入配料。 如果是这种情况,则应在关联中定义它:

has_many :ingredients, :include => true ...

如果您想在某些情况下专门装入配料,则需要按照上一个答案中的说明进行操作(已被否决,但我不知道为什么。):

Recipe.includes(:recipeingredients).first(5)

检查SQL查询输出以显示其好处。

这将一次性获取一个配方以及所有关联的配料和配方成分:

r = Recipe.includes(:ingredients, :recipeingredients).find(1)

之后,您可以像这样循环(HAML视图):

- r.recipeingredients.each do |ri|
  Ingredient:
  = ri.ingredient.name
  quantity:
  = ri.quantity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM