Spyros
Spyros

Reputation: 48706

How do you handle current user and a list of users?

i'm having a situation (pretty standard for everybody i guess), where i have to do two things :

  1. If a user asks for /user path, i have to present his/her personal information.

  2. If a user asks for /user/:id path, i have to present information about that particular user, or the current user information if :id matches the current_user id.

There are definitely many ways to do that, but what is the best approach ? Should i have 2 different routes like /show/:id and /show_current, handled by different actions, or just have a /show/:id and do the handling in that action ?

Bear in mind that if this is the current view, i need to render a different more detailed view than the one about another view. I think the latter is probably the better way,but what do you think ?

Upvotes: 2

Views: 213

Answers (2)

mu is too short
mu is too short

Reputation: 434985

If the current user is, say, 42 then /user/42 and /user would display the same information but /user/23 would display a stripped down public version of 23's data. So, the handler for /user/:id will have to know about the special case of :id being the current user; the handler for /user will also have to know about this special case as that's all it does.

If you use two routes then you'll either be duplicating code, wrapping the real code in an extra layer, or some other bit of busy work. I'd just send them both to the same controller method and that could start with something like this:

user = params['id'] ? User.find(params['id']) : current_user

And then later on you handle the special case of the requested user being the current user in just one place with something simple:

if(user == current_user)
    # show the full blob of information
else
    # show just the limited public information
end

You could, of course, slice it up into a bunch of little methods, such as show_current_user_info and show_other_user_info, inside the controller. The handler for /user could just be a call to show_current_user_info; the /user/:id handler could call show_current_user_info or show_other_user_info depending on what :id is. This approach smells like pointless layering to me.

Upvotes: 2

Steve Ross
Steve Ross

Reputation: 4144

In RESTful routing, you've described users_path and user_path(some_id). These map to User#index and User#show. The index method is normally a list of users, but if you are wanting index to show the current_user personal information, you can certainly do that. If you also need a list method, just add it to your controller and create a route to it.

Upvotes: 1

Related Questions