【问题标题】:Rails Time to String - either ignores function or acts randomlyRails Time to String - 忽略函数或随机动作
【发布时间】:2013-12-14 09:04:18
【问题描述】:

在 Ruby on Rails 3 中,我尝试修改我的 Model 数据集的日期以仅显示小时和分钟,然后我将其作为 AJAX 字符串返回。

我的代码如下:

 list_of_time_fields = [:a, :list, :of, :symbols]
 result = Model.where(conditions).take(100)
 result.each { |row|
        list_of_time_fields.each { |field|
            row[field] = row[field].strftime("%H:%M") unless row[field].nil?
        }
    }
 return result

对于某些字段,我得到整个时间字符串(类似于yyyy-mm-ddTHH:MM:ssZ),而对于其他字段,我得到null,即使该字段不为空。区别在于返回字符串的是 MySQL 中的TIME 字段,而其他的是DATETIME

我检查了 Rails 将这些列映射到的类型,所有内容都是 class Time

如果你能指出我应该看哪些东西那就太好了。

【问题讨论】:

  • 您是否以 JSON 格式返回数据?
  • 是的,带有render json: result

标签: mysql ruby-on-rails ruby activerecord time


【解决方案1】:

将时间字符串分配给属性时:

row[field] = row[field].strftime("%H:%M")

Rails 解析字符串并创建一个新的日期时间(实际上是 ActiveSupport::TimeWithZone)对象:

user = User.new
user.created_at = "01:00"
#=> "01:00"
user.created_at
#=> Thu, 28 Nov 2013 01:00:00 CET +01:00

使用自定义哈希是可行的。比如:

result = Model.where(conditions).take(100).map { |model|
  {
    id: model.id,
    time_field: model.time_field.try(:strftime, "%H:%M")
  }
}
render json: result

JBuilder 可能是另一种选择。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 2021-05-25
  • 2011-06-11
相关资源
最近更新 更多