簡體   English   中英

顯示活動記錄關系中的對象屬性

[英]showing object attributes from active record relations

我嘗試在quantity.amount行之后顯示gredit.name,但不知道如何從對象中檢索名稱

Ingredient.where(ingredient_id: quantity.ingredient_id)

哪個返回

#<Ingredient::ActiveRecord_Relation:0x8e30590> 

def show
  @recipe = Recipe.find(params[:id])
  @quantities = @recipe.quantities
  @ingredients = @recipe.ingredients
end

- @quantities.each do |quantity|
  %ul
    %li
      = quantity.amount
      = Ingredient.where(ingredient_id: quantity.ingredient_id)

class Quantity < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
  accepts_nested_attributes_for :ingredient, :reject_if => :all_blank
end

class Ingredient < ActiveRecord::Base
  has_many :quantities
  has_many :recipes, :through => :quantities
end

為什么這樣做,您已經在“數量”模型中有了關系名稱,因此可以直接訪問它:

= quantity.amount
= quantity.ingredient.name

並且如果數量沒有數量,那么您應該說以下內容以免產生錯誤:

= quantity.ingredient.try(:name)    

在這種情況下,我需要的是

class Recipe
  has_many :quantities
end

class Quantity < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end

class Ingredient < ActiveRecord::Base
end

然后在控制器中,我們使用預先加載來防止在循環中進行查詢

def show
  @recipe = Recipe.includes(quantities: :recipe).find(params[:id])
end

在數量模型中添加一個委托

class Quantity < ActiveRecord::Base
  # relations and stuff

  delegate :name, to: :ingredient, prefix: :true, allow_nil: :true
end

風景

- @recipe.quantities.each do |quantity|
  %ul
    %li
      = quantity.amount
      = quantity.ingredient_name

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM