0

In my seed.rb

  puts 'DEFAULT Categories'
  categories = Category.create([{name:'cat1'},{name:'cat2'}, {name: 'cat3'} ])
  if categories.save
    puts "categories saved"
  else
    puts "categories save failed"
  end

I use this to set the default categories but the problem is that I can't if categories.save to see if all category item get saved and hence the seed.rb get passed So, how can I see if an array get saved? (All of its elements) Thanks

ZK Zhao
  • 19,885
  • 47
  • 132
  • 206

4 Answers4

0

Use create! instead of create. It'll raise an an exception if it fails to save.

Andy Waite
  • 10,785
  • 4
  • 33
  • 47
  • 1
    Much (if not most) of the time, blowing up the app with an exception because of a bad save is a bad idea. Better to check if Model.save returned true or false and then render the errors if necessary. – Nick Messick Apr 01 '13 at 17:40
  • For something user-facing, I would agree. But this is in a seed task. – Andy Waite Apr 01 '13 at 19:29
  • very true. In that case, blowing up the app during the seed might be what you need to do. – Nick Messick Apr 02 '13 at 15:55
0
if categories.all?(&:save)
  puts "categories saved"
else
  [...]
end
John Naegle
  • 8,077
  • 3
  • 38
  • 47
cthulhu
  • 3,749
  • 1
  • 21
  • 25
0

.create is creating the record. So, when you get to your if statement nothing happening because the save already happened during the create.

Change your .create to a .new, and you will be able to check if the save happened successfully:

puts 'DEFAULT Categories'
categories = Category.new([{name:'cat1'},{name:'cat2'}, {name: 'cat3'} ])  
if categories.save  
  puts "categories saved"  
else  
  puts "categories save failed"  
end  
Nick Messick
  • 3,202
  • 3
  • 30
  • 41
0
if categories.all.each(&:persisted?)
  puts "categories saved"
else
  [...]
end
Marcelo De Polli
  • 28,123
  • 4
  • 37
  • 47