gpt4 book ai didi

ruby-on-rails - 对象的未定义方法 `distance_of_time_in_words'

转载 作者:行者123 更新时间:2023-12-02 14:53:35 26 4
gpt4 key购买 nike

我正在使用 Rails 5.2.2 我的数据库中有许多空(无)字段,我创建了一个自定义方法来在我的模型中使用 distance_of_time_in_words 而没有错误。

  def my_distance_of_time_in_words
if self.accounts.blank?
"No Record Avaliable"
else
distance_of_time_in_words(self.accounts.first.updated_at,Time.now).titleize
end
end

我正在使用以下方法从 View 中传递我的对象:

<%= @customer.my_distance_of_time_in_words %>

它运行良好,我重新启动了我的电脑,它说:

undefined method `distance_of_time_in_words' for #<Customer:0x00007f43b98601d8>

这很奇怪,因为正如我所说,它按我的预期工作。但它现在不工作了。

最佳答案

默认情况下,日期助手在您的模型中不可用,因此您需要明确包含它们。

class Customer < ApplicationRecord
include ActionView::Helpers::DateHelper

def my_distance_of_time_in_words
if self.accounts.blank?
"No Record Avaliable"
else
distance_of_time_in_words(self.accounts.first.updated_at,Time.now).titleize
end
end
end

然而,更好的方法是使用辅助方法来完成您需要的操作,这样您就不需要显式包含 ActionView::Helpers::DateHelper,因为它已经可以用于你在那里:

module CustomersHelper

def my_distance_of_time_in_words(customer)
if customer.accounts.blank?
"No Record Avaliable"
else
distance_of_time_in_words(customer.accounts.first.updated_at,Time.now).titleize
end
end
end

关于ruby-on-rails - 对象的未定义方法 `distance_of_time_in_words',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54217443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com