简体   繁体   中英

Devise and Root Route

I am using devise (2.1.2) for the first time in a rails app. I've followed along w/ the install procedure and generated a User model. My setup is extremely generic and I have just two controllers. I was up and running and authenticating with no problems at all for hours yesterday. I was logging in and out and stopping and restarting my server without issue. Life was good. And then out of the blue when I try to visit /main/index (protected) its redirected to users/sign_in which makes sense, but I get this error

No route matches {:controller=>"devise/main"}

Here is routes.rb

get "bid/index"
get "main/index"
get "main/feed"
get "main/admin"
get "main/fullday"
match "bid/bid/:id/:starttime/:endtime/:color" => "bid#bid"
match "bid/delete/:id" => "bid#delete"
match "main/bidfeed/:id" => "main#bidfeed"
match "main/attr/:id/:field/:value" => "main#attr"

devise_for :users
root :to => 'main#index'

I don't really understand where "devise/main" came from and I don't understand why this failed so suddenly after I restarted the server :(

This usually happens when you are inside a namespaced controller (which is the case for Devise views).

On the link_to that caused the error, try prepending a slash on the controller name.

Check this issue on the Devise page on Github

why that happens : under the hood, the devise_for method, on your routes.rb, actually creates a namespace for your "devise controller". The devise view that you created belongs to that "devise controller", and thus, when you use link_to :controller => 'bla', Rails will try to find the controller bla` inside the devise namespace, which does not exist, and kaboom!

Ideally, you should use resource based Routes, or named routes. That would minimize this kind of problem, and collateraly make your code easier to read and maintain (well, this is usually the case, but this is by no means a silver bullet- use this advice with care).

If you are still curious, I would recommend reading the guides page about routing (very simple and straight to the chase), and the documentation of url_for (really, reaaaally helpful if you are serious about Rails).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM