티켓 모델이 있으며 사용자는 주어진 일련 번호부터 일련의 티켓을 구입할 수 있습니다. 사용자는 구매하고자하는 티켓의 수를 선택하고 컨트롤러는 해당 수의 티켓과 상점을 데이터베이스에 생성합니다. 그러나 하나의 티켓을 저장하지 못하면 트랜잭션은 롤백되어야하지만이 경우에는 그렇지 않습니다.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
...
또한 리디렉션 정확하지만 통지 게재하지 않는다.
이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
이 코드는 트랜잭션에서 작동하지만 슬프게도 오류 통지가 나오지 않습니다. –
'render json : @ ticket.errors'가 배열을주었습니다. 더 이상 편집 할 수없는 이유가있을 수 있습니다. – apneadiving
html 형식의 Flash [: notice]를 사용해야했습니다. –