6

I'm trying to use the button_to rails helper. I wrote the following code:

<%= button_to 'Edit Item', edit_item_path(@item), :class => 'mark-button' %>

and got the following error message

No route matches "/items/1/edit"

But when I refresh the page it goes to the appropriate action. The URL of the page i get is localhost:3000/items/1/edit which is the correct URL. If I switch the button_to command to link_to the page loaded with no errors. Meaning this code:

<%= link_to 'Edit Item', edit_item_path(@item), :class => 'mark-button' %>

loads fine. Maybe there is some feature of button_to I'm not aware of, but I am at a lost.

laurent
  • 88,262
  • 77
  • 290
  • 428
Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98

3 Answers3

5

I think you might be misusing button_to. I've always thought that if you're linking to the edit action, you should be using link_to. Buttons seem to be for actions that need to post/put data such as updating a form or deleting a record.

Update:

By default, button_to uses POST instead of GET. Hence it working when you just visit the URL (ie GET).

Peter Brown
  • 50,956
  • 18
  • 113
  • 146
  • How can i override this feature? – Nachshon Schwartz Jan 16 '11 at 23:25
  • If you want it to look like a button, I would use link_to and use a CSS class that makes your link look like a button. Great article here: http://www.smashingmagazine.com/2009/11/18/designing-css-buttons-techniques-and-resources/ – dontangg Jan 16 '11 at 23:27
  • 2
    @nayish you can set the method to get: `button_to 'edit', edit_item_path(@item), :method => :get` – Peter Brown Jan 16 '11 at 23:31
2

button_to defaults to POST, and link_to defaults to GET.

If you really need button_to you can change the default method to GET for edit and other links.

for ex:

<%= button_to 'Edit', edit_user_path(@user), :method => :get %>
pinku
  • 1,139
  • 2
  • 9
  • 25
-2

Ruby -v 2.8.6, Rails 6.1.4.1

<%= button_to 'Edit', edit_item_path(item), :method => :get %> because with expression (@item) you do not define the object you want to edit, because (@item) it is not a specific object, there are several and you need to define only the one you want to edit, :method => :get this method is perfect

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 14 '21 at 16:21