Ruby-on-rails 将 link_to 更改为 button_to 时“没有路由匹配 [POST]”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12475299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:46:47  来源:igfitidea点击:

"No route matches [POST]" when changing link_to to button_to

ruby-on-railsbuttonhyperlink

提问by Jazz

I have this piece of code:

我有这段代码:

<%= link_to "New User", new_user_path, :class => "button"  %><br />

which works fine, but when I change it to,

效果很好,但是当我将其更改为

<%= button_to "New User", new_user_path, :class => "button"  %><br />

I get this error

我收到这个错误

No route matches [POST] "/users/new"

没有路由匹配 [POST] "/users/new"

Any help at all will be appreciated.

任何帮助都将不胜感激。

回答by megas

Jesus Rodriguez is right about POST and GET, but if you really need the button you can simply override the default method:

耶稣罗德里格斯关于 POST 和 GET 是正确的,但如果你真的需要按钮,你可以简单地覆盖默认方法:

<%= button_to "New User", new_user_path, :class => "button", :method => :get  %>

回答by Jesus Rodriguez

The "link_to" is looking for a /users/newusing GET.

“link_to”正在使用GET寻找/users/new

The "button_to" is looking for a /users/newusing POST

“button_to”正在使用POST寻找/users/new

If you create the routes for a controller using:

如果您使用以下方法为控制器创建路由:

resources :user

By default, /users/newis a GETand not POSTso, the second line doesn't find any route.

默认情况下,/users/newGET而不是POST,所以第二行找不到任何路由。

If you are thinking to change that action to POSTI think that you should forget about it.

如果您正在考虑将该操作更改为POST,我认为您应该忘记它。

回答by Acronin3

Instead of forcing button_to to use a non-default method, you can also send a class to link_to.

除了强制 button_to 使用非默认方法,您还可以向 link_to 发送一个类。

<%= link_to "New User", new_user_path, :class => "button" %>

回答by madmed

button_to defaults to POST, and link_to defaults to GET, this is why links_to worked. You can force button_to to use GET:

button_to 默认为 POST,link_to 默认为 GET,这就是 links_to 起作用的原因。您可以强制 button_to 使用 GET:

<%= button_to "New User", new_user_path, :class => "button", :method => :get %>

You can get more information about button_to options here: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to

您可以在此处获取有关 button_to 选项的更多信息:http: //api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to