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 !
Adam
September 30, 2008, September 30, 2008 03:29, permalink
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
TimK
September 30, 2008, September 30, 2008 03:39, permalink
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...
TimK
October 1, 2008, October 01, 2008 03:41, permalink
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
Adam
October 1, 2008, October 01, 2008 05:19, permalink
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
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.