Orsay Orsay - 5 months ago 65
Ruby Question

Rails: Undefined method in model

I'd like to convert a unix time to human time before saving my object from an api.
But I cannot access to my method

format date
, it raise me :


undefined method `format_date' for 1467738900000:Fixnum


My model :

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

Answer

line['time'] is not an instance of your Conference class, so you can't call format_date method on it. Instead, for example, you can make format_date a class method:

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

And then call it like this:

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

The other option is to use a before_validation callback (attribute assignment will be as follows: conference.date = line['time'] and there is no need for format_date method):

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