if categories.all?(&:save)
puts "categories saved"
else
[...]
end
How to determine if an array is saved in rails?
-
31-03-2022 - |
Question
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
Solution
OTHER TIPS
Use create!
instead of create
. It'll raise an an exception if it fails to save.
.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
if categories.all.each(&:persisted?)
puts "categories saved"
else
[...]
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow