简体   繁体   English

如何处理或防止Ruby on Rails中的“仅允许发布请求”错误?

[英]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. 如果访客通过GET访问/ forgotten-password,则会显示空白页。 The log however shows an exception "ActionController::MethodNotAllowed: Only post requests are allowed." 但是,日志显示异常“ ActionController :: MethodNotAllowed:仅允许发布请求。”

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. 我认为访问者正在单击电子邮件中的链接,该链接切断了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. 我意识到我可以将GET路由添加到创建中,然后处理控制器中的错误,但是有什么告诉我有更好的方法。

Explicitly disabling :index from your routes means the /forgotten-passwords GET request is disabled. 从您的路由中显式禁用:index意味着/ forgotten-passwords GET请求已禁用。 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. 在index方法中,您可以创建一个说明情况的页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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