0

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
1
  • As the error suggests, line['time'] is a number, not an instance of your class Conference. And the reason is not in the code you posted. Commented Jul 2, 2016 at 15:32

2 Answers 2

1

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') }
Sign up to request clarification or add additional context in comments.

Comments

1

You are getting the date in unix time milliseconds. You can do like this

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

1 Comment

Thank you for the proposition it was my first idea but I wanted to do a method to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.