Help me refactor this nasty Ruby if/else statement

Posted by Suborx on Stack Overflow See other posts from Stack Overflow or by Suborx
Published on 2010-05-08T11:54:49Z Indexed on 2010/05/08 18:28 UTC
Read the original article Hit count: 203

Filed under:
|

Hello, so I have this big method in my application for newsletter distribution. Method is for updating rayons and I need to assign a user to rayon. I have relation n:n through table colporteur_in_rayons which has attributes since_date and until_date.

I am a junior programmer and I know this code is pretty dummy :) I appreciate every suggestion.

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

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby