ActiveRecord事务并没有回滚整个事务



我有一个票证模型,用户可以从给定的序列号开始连续购买票证。用户选择他们想要购买的票的数量,控制器生成该数量的票并存储在数据库中。但是,如果一个票证未能保存,则事务应该回滚,但在这种情况下没有。

tickets_controller.rb

...
def create
  number = params[:ticket_qty].to_i
  @tickets = Array.new
  number.times do |n|
    t = Ticket.new(ticket_params)
    t.serial_number = t.serial_number.to_i + n 
    @tickets.push(t)
  end
  respond_to do |format|
    ActiveRecord::Base.transaction do 
      @tickets.each do |t| 
        if t.save
          format.html { redirect_to tickets_path, notice: "#{number} #{"ticket".pluralize(number)} successfully created." }
          format.json { render :show, status: :created, location: tickets_path }
        else
          format.html { render :new, notice: "Some tickets have errors, check the serial number range" }
          format.json { render json: @ticket.errors, status: :unprocessable_entity }
        end
      end
    end
  end
end
...

此外,重定向是正确的,但没有显示任何通知。

要在出现错误时回滚事务,请将t.save替换为t.save!

这将导致:

respond_to do |format|
  begin 
    ActiveRecord::Base.transaction do 
      @tickets.each &:save!
      format.html { redirect_to tickets_path, notice: "#{number} #{"ticket".pluralize(number)} successfully created." }
      format.json { render :show, status: :created, location: tickets_path }
    end
  rescue ActiveRecord::ActiveRecordError => e
    format.html { render :new, notice: "Some tickets have errors, check the serial number range" }
    format.json { render json: e.message, status: :unprocessable_entity }
  end
end

另一个选项是保存所有记录并根据结果手动触发回滚:

Ticket.transaction do 
  @save_results = @tickets.map(&:save)
  raise ActiveRecord::Rollback unless @save_results.all?
end
respond_to do |format|
  if @save_results.all?
    format.html # ...
    format.json # ...
  else
    format.html # ...
    format.json # ...
  end
end

您可以使用@save_results来显示失败记录的数量:

"#{@save_results.count(false)} tickets have errors, ..."

相关内容

  • 没有找到相关文章

最新更新