Victor Ronin
Victor Ronin

Reputation: 23288

Accepting timestamp as an integer in Rails

I am trying to POST a json object to the rails app.

One of the field of this object is a a pretty much timestamp. It's saved in a 'timestamp' member in a model.

Rails handles well a lot of datetime formats represented by a string (as example I can send "December 24, 2015 at 9:46:24 PM PST" and it will work).

However, rails will reject an object if I try to send an integer (unix time) timestamp.

Is this standard behavior (or am I missing something)

Upvotes: 1

Views: 1417

Answers (2)

Hieu Pham
Hieu Pham

Reputation: 6692

We can easily do this by defining like a proxy attribute in your model

attr_accessible :integer_timestamp

def integer_timestamp
  timestamp.to_time.to_i
end

def integer_timestamp=(value)
  self.timestamp = value.blank? ? nil : Time.at(value.to_i)
end

Upvotes: 1

RAJ
RAJ

Reputation: 9747

You need to convert your epoch time explicitly.

It can be:

class MyModel < ActiveRecord::Base
  def my_attr_name=(timestamp)
    dt = begin
           timestamp.to_datetime
         rescue ArgumentError
           DateTime.strptime(timestamp,'%s')
         end

    write_attribute :my_attr_name, dt
  end
end

Upvotes: 0

Related Questions