Benito Serna Tips and tools for Ruby on Rails developers

What to do when you need a button_to within a form in Rails

June 5, 2023

Imagine that you have a form to update a record (let’s say a product record) and inside the form, you are showing a list of images, and each image needs a button to remove it. You tried to use button_to but it doesn’t work because in html you can have form within a form. What do you do?

You can use the “form” attribute

You can use a button tag and define its form attribute. The value should be the id of a form located anywhere in the document.

For example, in the next code, for each persited image, we call render a button with a form attribute “delete_image_#{image.id}”.

<%= form_with(model: product) do |form| %>
  ...
  <div class="product-images">
    <% product.persisted_images.each do |image| %>
      <figure>
        <%= image_tag image %>
        <%= tag.button(
          "Remove",
          type: "submit",
          form: "delete_image_#{image.id}") %>
      </figure>
    <% end %>
  </div>
  ...
<% end %>

And later in the page, for each persisted image, we can render a hidden form with id “deleteimage#{image.id}” that will match the previous button.

<% product.persisted_images.each do |image| %>
  <%= form_with(
    model: image,
    url: product_image_path(product, image),
    method: :delete,
    id: "delete_image_#{image.id}") do %>
  <% end %>
<% end %>

Related articles

Weekly tips and tools for Ruby on Rails developers

I send an email each week, trying to share knowledge and fixes to common problems and struggles for ruby on rails developers, like How to fetch the latest-N-of-each record or How to test that an specific mail was sent or a Capybara cheatsheet. You can see more examples on Most recent posts or All post by topic.