【问题标题】:Displaying Date Time in rails 3.2 as in the database without conversion在 Rails 3.2 中显示日期时间,就像在数据库中一样,无需转换
【发布时间】:2014-11-25 11:15:10
【问题描述】:

有什么方法可以在 Rails 3 上显示数据库中的日期时间吗?

:created_at 存储为

“2014-11-25 10:55:56.445949”

在数据库中。我的 Rails 应用程序中到处都需要相同的格式。我在视图中使用了created_at_before_type_cast,它可以工作但无法获得 json 响应。我可以使用默认范围吗?如果是的话如何。谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 rails-activerecord


    【解决方案1】:

    您可以使用strftime 指定如何显示日期,然后在您的模型上定义一个新属性,该属性将返回您选择的格式:

    def created_at_formatted
      self.created_at.strftime("%Y-%M-%D %H:%M:%S.%L")
    end
    

    看看this link,它描述了所有的各种表示。

    【讨论】:

      【解决方案2】:

      我更喜欢使用 Active Model Serialization gem,它可以让你根据需要生成 json!它非常强大,现在人们正在使用它。

      https://github.com/rails-api/active_model_serializers

      在您的序列化程序文件中:

      您可以定义自己的数据。假设您有一个 Post 模型,并且您想为其生成 json 响应模型。您可以执行以下操作:

      class PostSerializer < ActiveModel::Serializer
        attributes :id, :date_for_json
      
        # look up :subject on the model, but use +title+ in the JSON
        attribute :subject, :key => :title
        has_many :comments
        def date_for_json
            object.created_at.strftime("Printed on %m/%d/%Y") #=> "Printed on 11/19/2007"
        end
      end
      

      当您声明时,现在在您的控制器中:

      render json: @products
      

      这会给你这样的输出:

      [{id: 1, date_for_json: "Printed on 11/19/2007", id: 2, date_for_json: "Printed on 11/19/2007"}, ....]
      

      嗯,我刚刚分享了我过去为自己采用的最佳做法。这将为您提供一些设计 api 的好主意。

      【讨论】:

      • 这次投票有什么理由吗?所以我可以考虑他们并修复我的答案或删除它!
      • 哦,有人投了反对票 :( 我只是想分享一下我认为最佳做法是什么 :(
      猜你喜欢
      • 1970-01-01
      • 2013-10-17
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多