2016-11-14 49 views
1
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

这怎么不工作? – ndn

+0

虽然你的代码可以缩短,但它应该工作得很好。 – Stefan

+0

此代码中的问题是第一张票已保存!我想回滚两张票@ndn – lolix

回答

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 
+0

这与原始代码具有相同的功能,不同之处在于它在发现无效代码后仍会尝试保存剩余的有效工单。 –

+0

...是的,我的不好:) – ttrmw