Rails: Flash error message if batch action fails partially

From FVue
Jump to: navigation, search

Problem

When doing a batch action on multiple objects, not each object might save successfully. How to report this in the flash message?

Environment

  • rails-7

Solution

invalids = []
batch_action_collection.find(ids).each do |oo|
  oo.foo = :bar
  invalids << oo unless oo.save
end
if invalids.count.zero?
  flash[:info] = 'All objects processed successfully.'
else
  flash[:error] = "#{invalids.count} #{invalids.first.model_name.human.pluralize(invalids.count)} " \
    "returned error: ##{invalids.pluck(:id).join(', ')}"
end
redirect_to collection_path

Comments

blog comments powered by Disqus