save an active records array

前端 未结 6 803
梦如初夏
梦如初夏 2021-02-05 07:28

I have an array like this

a = []

a << B.new(:name => \"c\")
a << B.new(:name => \"s\")
a << B.new(:name => \"e\")
a << B.new(:n         


        
6条回答
  •  -上瘾入骨i
    2021-02-05 08:16

    So I think we need a middle ground to Alexey's raising exceptions and aborting the transaction and Jordan's one-liner solution. May I propose:

    B.transaction do
      success = a.map(&:save)
      unless success.all?
        errored = a.select{|b| !b.errors.blank?}
        # do something with the errored values
        raise ActiveRecord::Rollback
      end
    end
    

    This will give you a bit of both worlds: a transaction with rollback, knowledge of which records failed and even gives you access to the validation errors therein.

提交回复
热议问题