我尝试在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
为什么这样做,您已经在“数量”模型中有了关系名称,因此可以直接访问它:
= quantity.amount
= quantity.ingredient.name
并且如果数量没有数量,那么您应该说以下内容以免产生错误:
= quantity.ingredient.try(:name)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句