0

I'm attempting to reformat a date being returned by from the database (Date format) as a formatted string (format: %m%d%y) in order for it to be output by a separate client application.

Formatting it on the client side is not an option as only the web app is under our control.

def as_json(options={})
  super(
    :except => [:id, :created_at, :updated_at],
    :include => {
      :children => {
        :except => [:created_at, :updated_at]
      }
    }
  ).merge(:tasks_total => self.tasks_total)
end

I've attempted to use a after_initialize callback, however that simply result in a nill value being passed to the client.

Any help much appreciated.

4

1 回答 1

0

为了解决 Rails 对 as_json 中的属性强制执行数据类型的问题,我使用了类似的东西,并带有一个哈希:

def as_json(options={})
  {
    name: name,
    date_of_birth: self.date_format(date_of_birth),
    more_info: more_info,
    children: children.map(&:as_json)
  }
end

调用是因为这个date_format模型实际上有多个日期需要以相同的方式格式化。

感谢@rbates 的帮助。

于 2013-02-07T14:50:09.203 回答