Take the 2-minute tour ×

Greetings all, newbie to Rails here. I'm currently having issues routing /profile to the current user's profile.

My route is as follows:

match "profile" => "users#show"

However, this is hitting me with the "Couldn't find User without an ID" error. I know it has to do with my show method in the Users Controller. That code is simply:

def show
@user = User.find(params[:id])

Now, I could add another method in my Users controller with "@user = current_user" and it works fine. However, it seems a bit redundant and would also require a copy of the show view page. From what I've gathered with Rails, it's all about keeping things neat and tidy.

I would appreciate it if someone could point me in the right direction. Thank you.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

RailsGuides states:

Because you might want to use the same controller for a singular route (/account) and a plural route (/accounts/45), singular resources map to plural controllers.

So I think you want to change your code to be the following

def show
    @user = !params[:id].nil? ? User.find(params[:id]) : current_user
share|improve this answer
Probably better to make sure that @user is always an actual User instance instead of an instance sometimes and an id other times. Otherwise good. –  DanneManne Feb 3 '11 at 3:12
sorry, typo. thanks for catching that. –  Steve Wilhelm Feb 3 '11 at 5:07
Thank you. I really have no idea how that works, but it does. I assume once I get a bit more savvy with Ruby, I'll understand it. –  Timb Feb 3 '11 at 5:31
@Timb, When you request a key from a Hash that does not exist, it returns nil. params is a Hash and you are checking to see if it contains a key value pair for :id. It will exist for the "profiles/17" example and it will return nil for the "profile" example. the ? : is a syntactic sugar for if then statement. If the params Hash contains an :id, then use it to find that user. If not, use the current_user. Glad to help. Could you select the check box under the "0" in the left column? Thanks. –  Steve Wilhelm Feb 3 '11 at 5:52
add comment

Your Answer


