【问题标题】:undefined local variable or method in own Model自己模型中未定义的局部变量或方法
【发布时间】:2018-04-07 05:58:57
【问题描述】:

我正在尝试在模型中创建一个名为“ingredient_name”的方法,但我不确定如何在它自己的模型类中定义“ingredient”。

用于#的未定义局部变量或方法`ingredient'

 class Ingredient < ApplicationRecord
    belongs_to :user
    validates :name,  presence: true
    def ingredient_name
        ingredient.try(:name)
    end
end

【问题讨论】:

  • 请分享您的成分模型的字段名称。

标签: ruby-on-rails class methods model


【解决方案1】:

这样使用

def ingredient_name
    self.try(:name)
end

【讨论】:

    【解决方案2】:

    尝试使用以下方法更改您的方法:

    def ingredient_name
        self.name
    end
    

    根据您提供的代码,ingredient_name 方法是一个实例方法。实例方法正在为您的实例查找名为 ingredient 的字段。

    【讨论】:

    • 另外,我认为我们可以删除try,这不是必需的。
    • @GaneshNavale “为您的实例命名为 ingredient 的字段。”本声明旨在解释作者目前的工作。
    猜你喜欢
    • 2015-12-04
    • 2017-01-26
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多