帮我重构这个讨厌的Ruby if/else语句

Sub*_*orx 1 ruby ruby-on-rails

所以我在我的通讯发布申请中有这个大方法.方法是更新人造丝,我需要将用户分配给人造丝.我有关系n:n通过表colporteur_in_rayons有属性since_dateuntil_date.

我是一名初级程序员,我知道这段代码非常虚拟:)我很欣赏每一个建议.

def update
  rayon = Rayon.find(params[:id])
  if rayon.update_attributes(params[:rayon])
    if params[:user_id] != ""
      unless rayon.users.empty?
        unless rayon.users.last.id.eql?(params[:user_id])
          rayon.colporteur_in_rayons.last.update_attributes(:until_date => Time.now)
          Rayon.assign_user(rayon.id,params[:user_id])
          flash[:success] = "Rayon #{rayon.name} has been succesuly assigned to #{rayon.actual_user.name}."
          return redirect_to rayons_path
        end
      else
         Rayon.assign_user(rayon.id,params[:user_id])
         flash[:success] = "Rayon #{rayon.name} has been successfully assigned to #{rayon.actual_user.name}."
         return redirect_to rayons_path
      end
    end
    flash[:success] = "Rayon has been successfully updated."
    return redirect_to rayons_path
  else
    flash[:error] = "Rayon has not been updated."
    return redirect_to :back
  end
end
Run Code Online (Sandbox Code Playgroud)

FMc*_*FMc 5

def update
    rayon = Rayon.find(params[:id])

    unless rayon.update_attributes(params[:rayon])
        flash[:error] = "Rayon not updated."
        return redirect_to :back
    end

    puid = params[:user_id]
    empty = rayon.users.empty?

    if puid == "" or (not empty and rayon.users.last.id.eql?(puid))
        msg = "Rayon updated.",
    else
        msg = "Rayon #{rayon.name} assigned to #{rayon.actual_user.name}.",
        rayon.colporteur_in_rayons.last.update_attributes(
            :until_date => Time.now) unless empty
        Rayon.assign_user(rayon.id, puid)
    end

    flash[:success] = msg[msg_i]
    return redirect_to rayons_path
end
Run Code Online (Sandbox Code Playgroud)