Freewind
Freewind

Reputation: 198258

How to add action 'current_user' to a restful 'user'?

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.

Upvotes: 3

Views: 491

Answers (3)

Harish Shetty
Harish Shetty

Reputation: 64363

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)

Upvotes: 1

Peter Brown
Peter Brown

Reputation: 51707

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

Upvotes: 2

Freewind
Freewind

Reputation: 198258

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?

Upvotes: 4

Related Questions