1

所以我在我的 routes.rb 中有这一行 match 'calculate' => 'index#calculate' 并且在尝试加载索引页面时它给了我一个错误:

match如果未指定 HTTP 方法,则不应在路由器中使用该方法。如果您想将您的操作公开给 GET 和 POST,请添加via: [:get, :post]选项。如果您想将您的操作公开给 GET,请get在路由器中使用:而不是:匹配“controller#action”做:获取“controller#action”

基本上,它是一个简单的应用程序,它从表单中获取一个数字,然后在对其进行一些计算后将其打印出来。但我现在被这个错误困住了......

我该如何克服这个错误?

4

3 回答 3

0

To overcome this error replace your match statement with a get statement

Replace:

match 'calculate' => 'index#calculate'

With:

get 'calculate' => 'index#calculate'

The reason for Rails suggesting that you use get instead of the more generic match is improving security by forcing you to make a conscious api design decision. A GET request is different from a POST request. A POST means 'change'; that request changes something, it modifies the system. A GET means 'give this page'. It does not change anything.

I assume your endpoint returns the result of some sort of calculation. You may argue that since the calculation does not change anything, a GET request is the way to go. You can also argue that this endpoint won't always return the same value for the same input (maybe?) in that case you may want to say that this is a POST, since you are not getting a unique resource.

I believe this is test app that you are making. Depending on what aspect of rails do you want to focus your learning on you may want to choose one, implement both and see what changes, or just flip a coin :)

The match method used to work in the way you used it, but since rails 4 this was changed to require this explicitness.

Docs: http://guides.rubyonrails.org/routing.html#http-verb-constraints

于 2013-10-15T23:10:05.027 回答
0

这个错误在 Rails 4 中被抛出,因为如果不是很小心,使用 match 会为跨站点脚本 (XSS) 开辟一条路线。从您的描述中很难判断您实际需要哪些路由,但如果您正在提交表单,您很可能只需要一个用于初始加载表单的 get 路由和一个 post 路由作为发送表单数据的位置.

要修复此错误,只需按照错误消息给出的说明进行操作,然后使用:

match 'calculate' => 'index#calculate', via: [:get, :post]

或者

get 'calculate' => 'index#calculate'

取决于您需要哪些路线。

于 2013-10-15T23:07:47.770 回答
0

您正在寻找:

match 'calculate', :to => 'index#calculate'

这将创建 GET 和 POST 路由。除非您两者都需要,否则无需使用“匹配”。您尝试做的可能只需要一条 GET 路线:

get 'calculate' => 'index#calculate'
于 2013-10-16T03:32:35.550 回答