Sachin Prasad
Sachin Prasad

Reputation: 5411

update the value of array of objects in rails

I'm retrieving data from database in ruby on rails.I have to update the Date retrieved with a new formatted date in controller.
Something like this one:-

   @events = 'My Query.'
   @events.each do |eventdata|
      # Since the date is in utc i have to convert it in users time zone.
      eventdata.start_date = eventdata.start_date.strftime("%Y-%m-%d %H:%M:%S")
    end

But its not working. Need some help on this.

Upvotes: 0

Views: 446

Answers (2)

rorra
rorra

Reputation: 9693

This is a monkey patch to format the date of all the DateTimes when being converted to json:

class ActiveSupport::TimeWithZone
  def as_json(options = {})
      strftime('%Y-%m-%d %H:%M:%S')
  end
end

put that on

/config/initializers/json_date_path.rb

and that's all.

Upvotes: 2

rorra
rorra

Reputation: 9693

You cannot change the format of the field, its a DateTime, you will have to use a method for that

def formated_start_date
  start_date.strftime("%Y-%m-%d %H:%M:%S")
end

However, you can change the format of the datetimes for all the database records, by creating the file config/initializers/date_time_formats.rb and add some content like

Time::DATE_FORMATS[:default] = "%Y-%M-%d %H:%M:%S"

Upvotes: 2

Related Questions