Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Devise with resources :users in Rails

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!

like image 559
Bazley Avatar asked Feb 19 '11 14:02

Bazley


3 Answers

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.

like image 162
Vlad Gurovich Avatar answered Nov 10 '22 10:11

Vlad Gurovich


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

like image 24
David Sulc Avatar answered Nov 10 '22 10:11

David Sulc


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

like image 3
jasmo2 Avatar answered Nov 10 '22 11:11

jasmo2