【问题标题】:Change the date format of created_at in as_json更改 as_json 中 created_at 的日期格式
【发布时间】:2018-04-17 06:12:30
【问题描述】:

我对 ruby​​/rails 了解不多。我的应用目前正在生成一些 json 供消息总线使用:

  message: act.as_json({
    only: [:id, :body, :direction, :kind, :sent, :is_read, :created_at, :call_tag],
    methods: [:delivering?, :attach_list, :voicemail_url, :status, :status_msg]
  })

数据恢复正常,唯一的问题是 created_at 日期的格式不理想:2018-04-17 01:57:32 UTC。我想要它在 iso8601 中:2018-04-17T01:54:20.026Z。在我的控制器中,正在使用 jbuilder 并以正确的格式返回 json。我对解决方案的搜索使我找到了 ActiveSupport,试图以某种方式在消息总线、to_json 等的发布方法中使用 jbuilder。有没有办法将created_at 设置为自定义值/格式?如果不是,那么 as_json 使用这种其他格式而 jbuilder 使用 iso8601 是否有原因?谢谢

【问题讨论】:

  • as_json 是 json 本身的字符串化版本。时间戳字符串(例如 Time.now.to_s)给出“2018-04-17 01:57:32 UTC”。使用 "2018-04-17 01:57:32 UTC".to_time.iso8601 应该可以解决您的问题

标签: ruby-on-rails json


【解决方案1】:

您可以覆盖相应模型上的 created_at

class Model < ActiveRecord::Base
  def created_at
    attributes['created_at'].strftime("%m/%d/%Y %H:%M")
  end
end

当然不要忘记根据需要调整格式

然后调用 .created_at 应该以您指定的格式返回值

【讨论】:

    【解决方案2】:

    Rails 6 Override created_at 无处不在

    class ApplicationRecord < ActiveRecord::Base
      def created_at
        attributes['created_at'].strftime("%m/%d/%Y %H:%M")
      end
    end
    

    或本地化

      include ActionView::Helpers::TranslationHelper
      #...
      def created_at
        l(attributes['created_at'],  :format => "%d %B /%Y %H:%M")
      end
      #...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 2011-06-05
      • 2016-11-22
      相关资源
      最近更新 更多