简体   繁体   中英

rails 3 including fields from joint table

I have the folowing structure:

Database:

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

Models:

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">]

What I would like achive is to be able to reach recipeingredients.quantity and recipeingredients.unit in r.ingredients.

I believe it could be achieved by changing the query somehow so that it returns something like SELECT * FROM "ingredients" INNER JOIN...

My goal is to be able to list the quantities as well as the properties of ingredients using one for cycle in the view.

Is there a way to do it? So far did not work anything what I found on forums.

Depends whether you want it sporadically or all the time, that is, always load the ingredients everytime you load a recipe. If that is your case, then you should define it in the association:

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

If you want to specifically load the ingredients on some cases, then you need to do as specified in the previous answer (which was downvoted, but I don't know why.):

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

check the SQL query output to visualize the benefits.

This will fetch a Recipe and all connected Ingredients and RecipeIngredients in one go:

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

After that you can loop like this (HAML view):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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