0

I have a rails 3 model with a Date field. when i render the model as json, the date field is returning the date and time. It should only return the date, because this is a Date field not a DateTime field.

how do I make my model return only the date for my Date fields, when rendering to json?

i've tried overriding the as_json methods of TimeWithZone and Date, as talked about in these 2 questions, but that's not working for me.

fwiw, we're using ruby 1.9.2, rails 3.0.7, mongodb and mongoid 2.0.2. I know our version of mongo/mongoid does not support a "Date" field type, specifically. it gets stored as a UTC time. i'm trying to get the data to look like it's just a date, on the way out to the client via json.

Community
  • 1
  • 1
Derick Bailey
  • 72,004
  • 22
  • 206
  • 219

1 Answers1

2

Just override the date getter in your class (assuming your date field is called date):

class YourClass < ActiveRecord::Base
  def date
    self[:date] && self[:date].to_date
  end
end

This way whenever you call some_record.date it will convert the TimeWithZone object to a Date object before returning it.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182