【问题标题】:Access attributes from an associated model rails 3从关联的模型导轨访问属性 3
【发布时间】:2012-12-03 01:12:29
【问题描述】:

我想在食谱显示视图上显示每个食谱的成分,成分在一个名为成分的单独模型中,但与食谱模型具有belongs_to关系

所以当我调用用户名时,例如我使用

@recipe.user.name

这是因为属性在配方模型中,我在配方助手中有一个方法,就像这样

  def ingredient_names(ingredients)
  if ingredients
  ingredient_array = ingredients.map {|ing| ing.ingredient_name}
  ingredient_array.join("\n")
  end
  end

所以我想我可以打电话

@recipe.ingredient_names

但我得到一个未定义的方法错误..

然后我认为我必须传递参数成分名称(列名)

@recipe.ingredient_names(:ingredient_name)

但仍然得到未定义的方法错误

当我这样做时

<%= @recipe.ingredients(:ingredient_name) %>

我得到这个作为输出

[#<Ingredient id: 71, ingredient_name: "Ingredient 1", recipe_id: 56, created_at: "2012-11-29 19:29:25", updated_at: "2012-12-02 16:29:58">, #<Ingredient id: 76, ingredient_name: "ingredient 2", recipe_id: 56, created_at: "2012-12-02 16:29:59", updated_at: "2012-12-02 16:29:59">, #<Ingredient id: 77, ingredient_name: "ingredient 3", recipe_id: 56, created_at: "2012-12-02 16:29:59", updated_at: "2012-12-02 16:29:59">]

那么当我拥有belongs_to 和has_many 的关系时,我如何调用另一个模型的属性。我猜是一个简单的问题,但无法弄清楚

谢谢

【问题讨论】:

    标签: ruby-on-rails-3 model


    【解决方案1】:

    想出了解决办法,我需要先访问方法

    <%= ingredient_names @recipe.ingredients(:ingredient_name) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      相关资源
      最近更新 更多