Help me refactor this nasty Ruby if/else statement
- by Suborx
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