Combining Devise with resources :users in Rails
Asked Answered
A

3

17

I am trying to combine Devise with a RESTful user resource using the following code in the routes.rb file:

resources :users, :only => [:index, :show]
devise_for :users

However the url localhost:3000/users/sign_up does not go to the devise sign up page, rather it produces the error "Couldn't find User with ID=sign_up", so it thinks the url is pointing to the show action of the users controller. I have found that swapping the order of the lines produces the intended behaviour:

devise_for :users
resources :users, :only => [:index, :show]

Now when you go to localhost:3000/users/sign_up you do indeed get the sign-up page, and going to localhost:3000/users/1 hits the show action of the users controller as intended.

My question is this: is changing the code order like this the correct way to get devise working together with the users resource? Or is there something deeper going wrong? I suspect that merely swapping those two lines of code round can't be the solution!

Acuna answered 19/2, 2011 at 14:57 Comment(0)
R
23

My advice in these situations is to check with rake routes In routes the order in which routes are defined matters since earlier routes take precedence.

So in your case resources :users, :only => [:index, :show] created a restfull /users/:id(.:format) route that pointed to {:action=>"show", :controller=>"users"} and when you went to Devise's sign up url /users/sign-up it considered 'sign-up' an :id of the user and naturally couldnt find it.

Now if you do the devise routing setup first, devise's routes take precedence over anything specified later and you get expected behaviour.

Rossman answered 19/2, 2011 at 19:8 Comment(1)
I still get the same error, even I wrote the devise before the resource. Do you have any idea why? thxCharland
R
16

Yes, that's the right way to do it (see https://github.com/plataformatec/devise/wiki/How-To:-Manage-users-through-a-CRUD-interface)

Rampart answered 19/2, 2011 at 15:1 Comment(0)
R
3

In the link David Sulc wrote is shown that you should write a prefix to device_for or resources Example:

devise_for :users, :path_prefix => 'my'
resources :users

Or your users

devise_for :users
scope "/admin" do
  resources :users
end

Both works well for me

Rabbet answered 25/2, 2015 at 16:57 Comment(1)
You should include the link in your answer.Gladwin

© 2022 - 2024 — McMap. All rights reserved.