Rails button_to fails with path doesn't exist

2019-03-29 11:39发布

问题:

Writing my first, very simple Rails application, a simple admin app to track work for one of our departments. The generated index page for people has a link_to on it to add a new person. I tried to change that to button_to and it fails saying the path /people/new doesn't exist, though obviously it does since link_to goes to the same place.

I'm using Rails 3/Ruby 1.9.2. I have this code on my /app/views/people/index.html.erb page:

<%= link_to 'New Person', new_person_path %>
<%= button_to "New", :controller => "people", :action => "new" %>

The link_to works. The button_to fails with this:

Routing Error No route matches "/people/new"

Also tried just

<%= button_to 'New Person', new_person_path %>

Same error. Odd.

回答1:

button_to defaults to the post method. Try putting :method => :get in there. This is why link_to works.



回答2:

There's a good explanation for this, as always :)

link_to uses GET as default, where button_to uses POST. And there's no POST route that matches, only a GET route.

If you want to use button_to, you can add :method => :get to your buttons params and it will use GET.



回答3:

Did you set up your routing options in config/routes.rb? Check if you have this in your routes.rb file:

resources :people

Check this guide for more informations about how routes work.



回答4:

Is your button_to inside a form? button_to creates a form of its own so this would create a form within a form and likely break routing.