【问题标题】:rails convert multiple columns query to strftime("%H" ) ... NoMethodError: undefined method `strftime'rails 将多列查询转换为 strftime("%H" ) ... NoMethodError: undefined method `strftime'
【发布时间】:2014-04-14 18:59:01
【问题描述】:

我一直在尝试从08:00:00 UTC to 8:00 转换 通过使用 strftime

这是带有字段的 Profile 模型。

class Profile < ActiveRecord::Base
  attr_accessible :sun, :mon, :wed, :tue, :thu, :fri, :sat
end

这是查询。

Profile.select('mon, tue, wed, thu, fri, sat, sun').where('usermodel_id = ?', 3).strftime('%H:%M')

错误:

NoMethodError: undefined method `strftime'

请你帮我转换格式:就像这样 周日:9:00,周一:9:00 等

我真的需要一些帮助,拜托

【问题讨论】:

    标签: ruby-on-rails rails-activerecord strftime


    【解决方案1】:

    您正在针对活动记录集合运行 strftime 方法,但该方法将针对 Ruby Time 对象运行。您必须对集合进行迭代,提取时间,然后您可以对它们调用 strftime

    例如:

    profile_collection = Profile.select('mon, tue, wed, thu, fri, sat, sun').where('usermodel_id = ?', 3)
    
    time_strings = profile_collection.map do |profile|
      %w(mon tue wed thu fri sat sun).map do |field|
        profile.send(field)
      end.map { |field| field.strftime('%H:%M') if field }.compact
    end
    

    它的作用:提取所有时间字段,然后对每个字段应用 strftime 方法;返回的数组将包含每个配置文件的数组,该数组又包含每天的时间字符串。

    【讨论】:

    • 非常感谢您的回复,对于那些日子不可用的个人资料,我有 sun 和 sun nil,因此我为 nil:NilClass 使用 gettig 未定义方法 `strftime'。
    • 更新了我的答案以说明这一点,compact 只是删除了当if 条件不满足时会发生的nil 值。
    • 天啊..你太棒了..愿你在生活中永远看不到悲伤;)
    • 如果您对这个答案感到满意,可以接受吗?谢谢!
    猜你喜欢
    • 2015-01-03
    • 2013-01-08
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多