Reputation: 4104
While making a form in Ruby on Rails I encoutered something peculiar, My submit
button performs the action of another button in the form.
<%=form_for(happening) do |f|%>
<%=f.text_field :name, class:"updateInput" %>
<%=f.submit "Save", class:"editButton" %>
<%= button_to "Delete", happening, method: :delete, class:"editButton"%>
<input type="datetime-local" value="<%= happening.get_html_date %>">
<%end%>
When I click the submit
button in this form, it will be routed to the destroy
action, rather than the update
one.
When I remove the delete
button, everything is routed properly.
Does someone have an explination for this? Thanks
Upvotes: 0
Views: 87
Reputation: 10673
You're seeing this behavior because there's more than meets the eye when you use the button_to
helper. button_to
doesn't just create a button -- it actually creates an entire form, with the actual button serving as the form's submit button.
By including your button_to
helper within a form, you're violating HTML's "no nested forms" rule and effectively adding a second submit button for your form which overrides the intended submit button. There's a difference between a submit button and an input of type button in HTML, and as I mentioned already, button_to
creates a submit button.
If you move that button_to
outside of your form as Ahmad pointed out, you'll have un-nested your forms and your view should behave as expected.
Consult the API doc for additional details.
Upvotes: 2
Reputation: 103
Your delete button should be outside your form.
<%=form_for(happening) do |f|%>
<%=f.text_field :name, class:"updateInput" %>
<%=f.submit "Save", class:"editButton" %>
<input type="datetime-local" value="<%= happening.get_html_date %>">
<%end%>
<%= button_to "Delete", happening, method: :delete, class:"editButton"%>
Upvotes: 1