0

For a project, who is an API, I want to be able to create "event" with a start, and a end date.

Sending datetime such as "Mon, 18 May 2015 12:56:10 UTC +00:00", isn't really easy, and it's a nightmare to parse in a front app.

What I want to achieve, is to allow my user to send a timestamp, and convert it to a datetime in DB.

However, has my fields are declared has Datetime in DB, when I try to create a new row with a timestamp, it's not working and return nil for those fields.

Event.create(start_at: Time.now.to_i, end_at: Time.now.to_i)

#<Event:0x007ff02424c838
  id: nil,
  start_at: nil,
  end_at: nil>

So far, I'd this :

before_validation :start_end_to_date

def start_end_to_date
    self.start_at = Time.at(self.start_date).to_time
    self.end_at = Time.at(self.end_date).to_time
end

In this case, my users send a start_date params, and I convert it to a Datetime.

Can you help me ?

cappie013
  • 2,354
  • 1
  • 22
  • 30
  • possible duplicate of [Convert to/from DateTime and Time in Ruby](http://stackoverflow.com/questions/279769/convert-to-from-datetime-and-time-in-ruby). You should really search for your problem before asking a new question. – MCBama May 18 '15 at 13:07
  • @Micah My question is not about HOW to convert "Timestamp" to "datetime". But how an activerecord field can accept a Timestamp when creating a new row. – cappie013 May 18 '15 at 13:09
  • It shouldn't need to. Databases are type safe for the most part and since activerecord is supposed to be associated with databases, it's typically type safe as well. I would suggest you convert the time objects to match what is in your database and not try storing the wrong type in the structure. – MCBama May 18 '15 at 13:18
  • I won't store the wrong type. I want my users to be able to send me a timestamp, THEN converting it in the right data type of my DB. – cappie013 May 18 '15 at 13:26
  • Then the duplicate flag I made is what you want. You want to receive a time object, and convert it to datetime. Exactly what that post tells you how to do. – MCBama May 18 '15 at 13:29
  • Of course, I might not understand the question at all, in which case I apologize – MCBama May 18 '15 at 13:47

1 Answers1

0

Without seeing your database schema I am just guessing at the real problem here, but I would try converting to datetime rather than time.

Time.at(Time.now.to_i).to_datetime

Also, rather than using a before_validation filter, you should create setters for start_at and end_at in your Event model.

def start_at=(val)
  write_attribute(:start_at, Time.at(val).to_datetime)
end

def end_at=(val)
  write_attribute(:end_at, Time.at(val).to_datetime)
end
Jarrod Spillers
  • 284
  • 2
  • 7