2016-04-15 46 views
1

我有行動,我在哪裏將組分配給應用的成員。基本上,我只是從窗體視圖中得到一個電子郵件列表,然後我有動作去捕捉它:從動作回滾模型 - 更改

我想知道的是,如果我可以回滾已經做出的更改,如果說第二個成員不存在,或者已經有一個組,我該如何回滾這些?

def group_create 
    @group = Group.new 
    params[:member].each { |m| 
    v = Volunteer.find_by_email(m[1]) 
    raise "#{m[1]} doesn't exist" unless v.present? 
    raise "#{v.email} is already in a group" if v.group.present? 
    v.group = @group 
    v.save! 
    } 
    @group.save 
rescue => error 
    flash[:error] = "Error: #{error}" 
ensure 
    respond_to do |format| 
    unless flash[:error].present? 
     flash[:notice] = 'Group Application succeded.' 
     flash[:joined] = true 
     format.html { redirect_to apply_group_path } 
    else 
     flash.discard 
     format.html { render :group } 
    end 
    end 
end 

我也想過已,是v.save和@ group.save移動到結束,並作出params[:member].each....另一個環,但是這將是ressources的相當浪費,做find_by_email-方法兩次,根據需要。

回答

2

我建議將您的非控制器邏輯分爲模型和ActiveRecord::Base.transaction包裝它:

ActiveRecord::Base.transaction do 
    @group = Group.new 
    params[:member].each { |m| 
     v = Volunteer.find_by_email(m[1]) 
     raise "#{m[1]} doesn't exist" unless v.present? 
     raise "#{v.email} is already in a group" if v.group.present? 
     v.group = @group 
     v.save! 
    } 
    @group.save 
end 

交易作爲圍繞SQL語句的保護性包裝,以確保對數據庫的修改時,所有操作一起成功纔會發生。

+0

那麼,製作一個Group.assign_members,這需要一個電子郵件數組,或沿着這些線? –