I've got a ticket model and users can buy tickets in series starting from a given serial number. The users choose the number of tickets they want to buy and the controller generates that number of tickets and stores in the database. However if one ticket fails to save, the transaction should roll back but in this case it is not.
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
...
Also the redirection is correct but no notice is showing up.
to have your transaction rolled back in case of error, replace t.save
with t.save!
This would result in:
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments