简体   繁体   中英

How to handle or prevent “Only post requests are allowed” error in Ruby on Rails?

I have a [somewhat] restful route setup with:

map.resources :forgotten_passwords,
              :as => 'forgotten-passwords',
              :except => [:destroy, :show, :delete, :index]
forgotten_passwords POST   
   /forgotten-passwords(.:format) 
   {:action=>"create", :controller=>"forgotten_passwords"}

   new_forgotten_password GET    
   /forgotten-passwords/new(.:format) 
   {:action=>"new", :controller=>"forgotten_passwords"}

   edit_forgotten_password GET    
   /forgotten-passwords/:id/edit(.:format) 
   {:action=>"edit", :controller=>"forgotten_passwords"}

   forgotten_password PUT    
   /forgotten-passwords/:id(.:format) 
   {:action=>"update", :controller=>"forgotten_passwords"}

If a visitor accesses /forgotten-passwords via GET they are presented with a blank page. The log however shows an exception "ActionController::MethodNotAllowed: Only post requests are allowed."

I would like to redirect to another action/view and display a pleasant error message to the visitor in this case. I think the visitors are clicking a link in an email that cuts off the end of the url.

I realize I could add a GET route to the create and then handle the error in the controller, but something tells me there's a better way.

Explicitly disabling :index from your routes means the /forgotten-passwords GET request is disabled. If you remove that you should have a functioning index method again.

Within the index method you can create a page that explains the situation.

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