【问题标题】:Rails: Undefined method in modelRails:模型中未定义的方法
【发布时间】:2016-11-04 19:51:28
【问题描述】:

在从 api 保存我的对象之前,我想将 unix 时间转换为人类时间。 但是我无法访问我的方法format date,这让我很兴奋:

1467738900000:Fixnum 的未定义方法 `format_date'

我的模特:

class Conference < ActiveRecord::Base
validates_presence_of :title, :date
validates :date, :uniqueness => true

 def self.save_conference_from_api
    data = self.new.data_from_api
    self.new.parisrb_conferences(data).each do |line|
      conference = self.new
      conference.title = line['name']
      conference.date = line['time'].format_date
      conference.url = line['link']
      if conference.valid?
        conference.save
      end
    end
    self.all
 end

 def format_date
   DateTime.strptime(self.to_s,'%Q')
 end

【问题讨论】:

  • 正如错误提示的那样,line['time'] 是一个数字,而不是您的类 Conference 的实例。原因不在您发布的代码中。

标签: ruby-on-rails ruby activerecord methods rails-activerecord


【解决方案1】:

line['time'] 不是您的Conference 类的实例,因此您不能对其调用format_date 方法。相反,例如,您可以将 format_date 设为类方法:

def self.format_date str
  DateTime.strptime(str.to_s,'%Q')
end

然后这样称呼它:

conference.date = format_date(line['time'])

另一种选择是使用before_validation回调(属性分配如下:conference.date = line['time'],不需要format_date方法):

before_validation -> r { r.date = DateTime.strptime(r.date.to_s,'%Q') }

【讨论】:

    【解决方案2】:

    您以 unix time 毫秒为单位获取日期。你可以这样做

    conference.date = DateTime.strptime(line['time'].to_s,'%Q')
    

    【讨论】:

    • 感谢您的提议,这是我的第一个想法,但我想做一个方法来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2012-05-21
    • 2021-11-02
    • 2015-06-14
    • 2013-04-28
    • 2015-12-10
    • 2017-01-02
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多