显示活动记录关系中的对象属性

时间:2015-04-25 18:56:44

标签: ruby-on-rails object activerecord

我尝试在quantitiy.amount行之后显示ingredient.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

2 个答案:

答案 0 :(得分:1)

为什么这样做,您已经在数量模型中拥有关系名称,因此您可以直接访问它:

= quantity.amount
= quantity.ingredient.name

如果数量没有数量,那么您应该说出以下内容以不引发错误:

= quantity.ingredient.try(:name)    

答案 1 :(得分:1)

在这种情况下我需要的是

class Recipe
  has_many :quantities
end

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

class Ingredient < ActiveRecord::Base
end

然后在控制器中,我们使用eager loading来阻止在循环中进行查询

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