【问题标题】:How to Use Helpermethod如何使用 Helper 方法
【发布时间】:2013-09-19 01:30:05
【问题描述】:

我在我的 application_helper 中创建了一个助手:

 def birthday(geburt)
   f = Date.today
   a = f.year - geburt.year
   a = a - 1 if (
     geburt.month >  f.month or 
    (geburt.month >= f.month and geburt.day > f.day)
    )
    a
 end 

现在我尝试在 模型中使用这个助手:

 patients = patients.where("birthday(geburtsdatum) >= ?", minimum) if minimum.present?

但是你怎么能在错误中看到我没有正确使用我的助手。 “geburtsdatum”是我的患者模型中的一个列。谢谢错误:

 SQLite3::SQLException: no such function: birthday: SELECT "patients".* FROM "patients"  WHERE (birthday(geburtsdatum) >= 15) ORDER BY vorname

我的新代码:

def find_patients
 patients = Patient.order(:vorname)
 patients = patients.where("nachname like ?", "%#{keyword}%") if keyword.present?
 patients = patients.where("#{geburtsdatum.get_birthday} >= ?", minimum) if   minimum.present?
 patients
end

我的新错误:

undefined local variable or method `geburtsdatum' for #<Search:0x4ee51b8>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    知道了,那么该方法适用于 Date 对象。

    正如您在该参考资料中提到的那样,包含 helper 是可行的,但不是一个好习惯。您可以快速修复它,没有错。

    仅供您参考,我认为更好的方法是在您的应用程序中扩展 Date 类以添加此类方法,然后您可以在像 some_date.process_birthday 这样的 Date 对象上调用它。

    您可以在/app,或/initializers,或/lib中添加此类文件(更好,但需要手动要求)。

    然后

    class Date
      def get_birthday
        f = Date.today
        a = f.year - self.year
        if (self.month >  f.month) || (self.month >= f.month && self.day > f.day)
          a = a - 1
        end 
        a
      end
    end
    

    【讨论】:

    • Geburtsdatum 是德语,在英语中 = 生日!但是你能进一步解释一下你的建议吗?谢谢
    • 我不知道,但这里写着stackoverflow.com/questions/489641/…
    • 谢谢,我将您的代码放入初始化程序 get_birthday.rb。然后在模型 patients.where("geburtsdatum.get_birthday >= ?", m..... 但不知何故它说没有这样的列: geburtsdatum.get_birthday !!!! 我该怎么写?谢谢
    • 首先,geburtsdatum 真的作为日期对象存在吗?如果是,则如果它们在字符串“#{geb.get_birthday} >= ...”中,则需要插值 ruby​​ 代码
    • 如果未定义,则需要定义。验证该变量或方法是否存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多