0

In Ruby on Rails 3 I'm trying to modify my Model dataset's dates to only show hours and minutes, which I then return as an AJAX string.

My code is the following:

 list_of_time_fields = [:a, :list, :of, :symbols]
 result = Model.where(conditions).take(100)
 result.each { |row|
        list_of_time_fields.each { |field|
            row[field] = row[field].strftime("%H:%M") unless row[field].nil?
        }
    }
 return result

For some fields I get the whole time string (something like yyyy-mm-ddTHH:MM:ssZ) and for others I get nulleven if the field is not null. The difference is that the ones that return strings are TIME fields in MySQL, whereas the others are DATETIME.

I've checked the types to which Rails maps these columns and everything is class Time.

If you can point which things I should look at It'd be great.

Pedro Montoto García
  • 1,672
  • 2
  • 18
  • 38

1 Answers1

1

When assigning the time string to the attribute:

row[field] = row[field].strftime("%H:%M")

Rails parses the string and creates a new datetime (actually a ActiveSupport::TimeWithZone) object instead:

user = User.new
user.created_at = "01:00"
#=> "01:00"
user.created_at
#=> Thu, 28 Nov 2013 01:00:00 CET +01:00

Using a custom hash would work. Something like:

result = Model.where(conditions).take(100).map { |model|
  {
    id: model.id,
    time_field: model.time_field.try(:strftime, "%H:%M")
  }
}
render json: result

JBuilder might be another option.

Stefan
  • 109,145
  • 14
  • 143
  • 218