【问题标题】:Conversion of String into DateTime works in console but not in request (Rails)?将字符串转换为 DateTime 在控制台中有效,但在请求中无效(Rails)?
【发布时间】:2019-12-08 09:21:05
【问题描述】:

我正在从 API 构建一个包装器,如果我使用 DateTime.parse() 将字符串转换为日期时间,它在检入控制台时可以正常工作,但不能在控制器方法索引请求中工作。我得到经典的“没有将 nil 隐式转换为字符串日期时间”错误。

这是我的代码:

class SodaApi < ApplicationRecord
  include HTTParty 

  def self.opportunities_api 
    client = SODA::Client.new({:domain => "data.cityofnewyork.us", :app_token => "<my api key>"})
    response = HTTParty.get("https://data.cityofnewyork.us/resource/n4ac-3636.json") 
      result = response.map do |r| 
      created_date = DateTime.parse(r['created_date'])
      end_date = DateTime.parse(r['end_date'])

      ### I build my wrapper here ###
    end
  end 
end

rails c 中,使用byebug,我可以创建created_date 的变量并将字符串转换为Datetime 没问题。

【问题讨论】:

    标签: ruby-on-rails ruby string datetime types


    【解决方案1】:

    返回的 JSON 中有超过 600 个元素没有 end_datestart_date

    response = HTTParty.get("https://data.cityofnewyork.us/resource/n4ac-3636.json")
    response.find_all{|r| r['start_date'].nil? }.count
    # => 665
    response.find_all{|r| r['end_date'].nil? }.count
    # => 665
    

    您需要处理这些情况,例如在这种情况下,通过设置默认值或不解析日期:

      def parse_date(string)
         return nil unless string
         DateTime.parse(string)
      end
    
      result = response.map do |r| 
        created_date = parse_date(r['created_date'])
        end_date = parse_date(r['end_date'])
        # ...
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多