Search code examples
ruby-on-railsformslink-to

How to create a link_to with a button to an action inside a form_for?


I have a resource called users. Inside the edit action, I have a form_for to edit user's information. I want to place a button inside the form to redirect to another action. So I am doing this:

<%= form_for @user, html: {class: 'form-horizontal'} do |f| %>
<div class="row">
  <div class="col-sm-8 col-sm-offset-2">

    <div class="form-group">
      <%= f.label :name, "Name", class: "col-sm-4 control-label"%>
      <div class="col-sm-8">
        <%= f.text_field :name, required: "required", class: "form-control" %>
      </div>
    </div>

    <div class="form-group">
      <%= f.label :email, "Email", class: "col-sm-4 control-label"%>
      <div class="col-sm-8">
        <%= f.email_field :email, required: "required", class: "form-control" %>
      </div>
    </div>

    <div class="form-group">
      <%= link_to root_path do %>
        <button class="btn btn-default" name="button">Go to Root</button>
      <% end %>
    </div>

    <%= f.submit "Save", class: "btn btn-default" %>

  </div>
</div>
<% end %>

The problem is that, when I click the "Go to Root" button, It process the form in the update action like if I have pressed the submit button. But If I change

<div class="form-group">
      <%= link_to root_path do %>
        <button class="btn btn-default" name="button">Go to Root</button>
      <% end %>
    </div>

for

<div class="form-group">
      <%= link_to root_path do %>
        Go to Root
      <% end %>
    </div>

It goes to te root_path. Why is it happening and Why I can't use a to create a link to another action inside this form?


Solution

  • By default a form button will have type submit. You need to specify that is of type button.

    Try the following:

    <button type="button" class="btn btn-default" name="button">Go to Root</button>