2722012beb9afcad75df5c9f2229fd8c

I'm using to_param to pass the login name as the id so the URLs are like /users/joe and /users/joe/edit - The user can only see the account that they are logged in with. This is called as a private before_filter on the Users controller to redirect a user that might change the login within the URL. It seems a little nasty.

1
2
3
4
5
6
7
8
9
10
11
def redirect_to_current_user
  if params[:id] != current_user.login
    if params[:action] == "show"
      redirect_to user_path(current_user)
    elsif params[:action] == "edit"
      redirect_to edit_user_path(current_user)
    end
  else
    @user = current_user
  end
end

Refactorings

No refactoring yet !

A8d3f35baafdaea851914b17dae9e1fc

Adam

September 30, 2008, September 30, 2008 03:29, permalink

1 rating. Login to rate!

If you need the @user instance variable, set it elsewhere.

1
2
3
def redirect_to_current_user
  redirect_to :id => current_user unless User.find(params[:id]) == current_user
end
2722012beb9afcad75df5c9f2229fd8c

TimK

September 30, 2008, September 30, 2008 03:39, permalink

No rating. Login to rate!

Excellent - much nicer... I edited User.find(params[:id]) to User.find_by_login(params[:id]) to accommodate for the to_param I mentioned, but otherwise such a better direction then what I was thinking...

2722012beb9afcad75df5c9f2229fd8c

TimK

October 1, 2008, October 01, 2008 03:41, permalink

No rating. Login to rate!

Adam, I was thinking about this today... couldn't I do something like this instead to remove the additional database call? Seems like I have all the data that needs the comparison without calling ActiveRecord? Thoughts...? Anyone?

1
2
3
def redirect_to_current_user
    redirect_to :id => current_user unless params[:id] == current_user.login
end
A8d3f35baafdaea851914b17dae9e1fc

Adam

October 1, 2008, October 01, 2008 05:19, permalink

No rating. Login to rate!

While that will work with what you have now, it makes several assumptions about the model which may not hold true in the future. You are, in a round about way, still determining if the one User instance is equal to the other User instance. From a strict MVC viewpoint it is best to let the model worry about model issues and let the controller worry about controller issues.

That said, it is often necessary to stretch the rules and I think there is merit in doing so here because of the technical limitations. However, may I suggest using to_param instead of login? It is closer to what you are trying to achieve.

1
params[:id] == current_user.to_param
2722012beb9afcad75df5c9f2229fd8c

TimK

October 1, 2008, October 01, 2008 12:17, permalink

No rating. Login to rate!

Thank you again Adam - I understand your point, and greatly appreciate the advice. Using to_param does seem like a better idea in case that to_param changes in the future.

Your refactoring





Format Copy from initial code

or Cancel