begin
ActiveRecord::Base.transaction do
installations.each do |installation|
id = installation.id
installation = current_user.installations.find_by(:id=> id)
@ticket = installation.tickets.new(ticket_params)
unless @ticket.save
raise ActiveRecord::Rollback
end
end
end
redirect_to '/tickets', notice: "done"
rescue ActiveRecord::Rollback
render action: "new", notice: "problem" and return
end
想象一下,我们有两张票,第一张票有效,第二张无效。在此代码中,将保存第一张票。但是我想在一次失败时回滚所有的票。 我怎么能这样做?
答案 0 :(得分:0)
你可以构建一个@ticket.save
的返回值集合,在它们上面调用.all?
,如果你得到一个虚假的提升回滚:
ActiveRecord::Base.transaction do
installations.each do |installation|
tickets_saved = []
id = installation.id
installation = current_user.installations.find_by(:id=> id)
ticket = installation.tickets.new(ticket_params)
tickets_saved << ticket.save
end
unless tickets_saved.all?
raise ActiveRecord::Rollback
end
end