0

I'm retrieving some API information in the following fashion

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

Most records get saved, no problem. But it seems some are missing height and some name. This causes NoMethodError with undefined method "height" or "name" for nil:NilClass, breaking the loop.

I don't mind if a single record doesn't have its value. How can I continue the loop after this?

I tried

if !save_api.save
  next
end

with no effect. (Edit: Also tried to save without "!"). Each block doesn't seem to accept rescue. What else is there?

Thanks so much in advance

Kasperi
  • 853
  • 7
  • 17

3 Answers3

0
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

im sure there is a more eloquent way to do it but I think this would work. you could also use a case statement which would be better but I don't feel like rewriting it all as such.

ruby_newbie
  • 3,190
  • 3
  • 18
  • 29
0

you can do so

Record.new do |record|
   if (record.respond_to?(:name) && record.respond_to?(:height)) 
   ...
end
epsilones
  • 11,279
  • 21
  • 61
  • 85
0

Simple do this:

fetch_api.each do |api|
  save_api = Record.new(name: api && api.name, height: api && api.height)
  save_api.save
end
Ahmad Hussain
  • 2,443
  • 20
  • 27