【问题标题】:Rails rescue/continue loop after each block NoMethodError在每个块 NoMethodError 之后 Rails 救援/继续循环
【发布时间】:2014-07-26 16:56:48
【问题描述】:

我正在按以下方式检索一些 API 信息

fetch_api.each do |api|
  save_api = Record.new(name: api.name, height: api.height)
  save_api.save! 
end

大多数记录都会保存,没问题。但似乎有些人缺少身高和一些名字。这会导致 NoMethodError 与 nil:NilClass 的未定义方法“height”或“name”,从而中断循环。

我不介意单条记录没有它的价值。在此之后如何继续循环?

我试过了

if !save_api.save
  next
end

没有效果。 (编辑:还尝试在不使用“!”的情况下保存)。每个区块似乎都不接受rescue。还有什么?

提前非常感谢

【问题讨论】:

    标签: ruby-on-rails api loops rescue


    【解决方案1】:
    fetch_api.each do |api|
      if api.name && api.height
        save_api = Record.new(name: api.name, height: api.height)
      elsif api.name
        save_api = Record.new(name: api.name)
      elsif
        save_api = Record.new(height: api.height)
      end 
        save_api.save! 
    end
    

    我确信有一种更雄辩的方法可以做到这一点,但我认为这会奏效。你也可以使用一个更好的case语句,但我不想这样重写它。

    【讨论】:

      【解决方案2】:

      你可以这样做

      Record.new do |record|
         if (record.respond_to?(:name) && record.respond_to?(:height)) 
         ...
      end
      

      【讨论】:

        【解决方案3】:

        这样做很简单:

        fetch_api.each do |api|
          save_api = Record.new(name: api && api.name, height: api && api.height)
          save_api.save
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-12
          • 2013-11-26
          • 2020-08-21
          • 1970-01-01
          • 2023-01-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多