【问题标题】:Ruby Api How to change time format to (HH:mm) using Active:model:Serializer?Ruby Api 如何使用 Active:model:Serializer 将时间格式更改为 (HH:mm)?
【发布时间】:2017-12-09 05:25:21
【问题描述】:

我的 db 表列名称是 hora (translation:hour): 输入时间。 (Postgres)。 我使用 Ruby 5.1 开发我的 API 我已经安装了 gem 主动模型序列化程序。我的问题是它以这种格式向我显示字段:“hora”:“2000-01-01T11:40:00Z”,但我只需要像这样的小时和分钟:11:40。 这是我的实际输出 json {"fecha":"2016-08-02","hora":"2000-01-01T11:40:00Z","importe":"86.0","medico":....}。

我需要这个: {"fecha":"2016-08-02","hora":"11:40","importe":"86.0","medico":...}

my table
|hora                  |
|time withotu time zone|
| 09:30:00             |
| 11:40:00             |
| 10:10:00             |

mycontroller#show
 # GET /atencions/1
  def show
    render json: @atencion
  end


my model
class Atencion < ApplicationRecord
    self.table_name = "atencion"
    belongs_to :medico
    belongs_to :paciente_planobrasocial
end

my model serializer
class AtencionSerializer < ActiveModel::Serializer
  belongs_to :medico
  belongs_to :paciente_planobrasocial
  attributes :fecha, :hora, :importe

end

有可能吗?我如何以及在哪里可以更改时间的格式... 提前谢谢...

【问题讨论】:

    标签: ruby api time-format


    【解决方案1】:

    如果我没记错的话,它是这样工作的:

    class AtencionSerializer < ActiveModel::Serializer
      belongs_to :medico
      belongs_to :paciente_planobrasocial
      attributes :fecha, :importe
      attribute :hora { object.hora.strftime "%H:%M" }
    end
    

    https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#overriding-attribute-methods

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 2013-09-09
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 2023-01-26
      • 2016-07-28
      相关资源
      最近更新 更多