views:

45

answers:

3

I have a model 'User', it's a restful resource, and has the default methods like 'index, show, new, create' and others.

Now, I want to define a new action 'current_user', to show the information of current logged-in user, which is different from 'show'.

When I use:

link_to current_user.name, :controller=>'users', :action=>'current_user'

The generated url is http://localhost:3000/users/current_user, and error message is:

Couldn't find User with ID=current_user

Shall I have to modify the routes.rb? What should I do?

I have searched for some articles, and still have no idea.

+3  A: 

Add

map.resources :users, :collection => {:current => :get}

Then, I use:

link_to 'current', current_users_path()

The generated url is:

http://localhost:3000/users/current

Now, everything is OK. Is this the best solution?

Freewind
Using the :collection parameter this way is not really the way it was intended to be used. Typically when you add a collection to a RESTful route, it is going to be for actions that work with multiple records. For example, you might use it to get a filtered set of users.Since this is likely an exception for this one model and won't be used for other resources, I personally would go with a named route such as: `map.current_user "users/current", :controller => :users, :action => :current`... and in the view: `link_to 'current', current_user_path`
Beerlington
+1  A: 

See my comment on the other answer for an explanation

map.current_user "users/current", :controller => :users, :action => :current

View:

link_to 'current', current_user_path
Beerlington
@Beerlington, I have modified as your answer, but such exception happened: `Couldn't find User with ID=current`. The generated url is: `http://localhost:3000/users/current`
Freewind
What does your controller action code look like? How are you trying to access the current user?
Beerlington
@Beerlington, it's OK now. I don't know why it's not yesterday, but OK now. Thanks:)
Freewind
+1  A: 

I would not add a new action for this. I would check the id passed to the show method.

class UsersController

 def show
   return show_current_user if params[:id] == "current"
   # regular show code
 end

private
 def show_current_user
 end

end

In the view use :current as the user id while generating path.

user_path(:current)
KandadaBoggu
@KandadaBoggu, your answer is good, but I have a small question: I have a 'show.erb' for action 'show', and a 'show_current_user.erb' for 'show_current_user'. It seems the 'show_current_user.erb' has never been used.
Freewind