【问题标题】:How to create a link_to with a button to an action inside a form_for?如何使用一个按钮创建一个链接到 form_for 内的操作?
【发布时间】:2017-11-22 20:03:56
【问题描述】:

我有一个名为 users 的资源。在编辑操作中,我有一个 form_for 来编辑用户信息。我想在表单内放置一个按钮以重定向到另一个操作。所以我这样做:

<%= 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 %>

问题是,当我单击“转到根目录”按钮时,它会在更新操作中处理表单,就像我按下了提交按钮一样。但是如果我改变了

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

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

它转到根路径。为什么会发生这种情况以及为什么我不能使用 a 在此表单中创建指向另一个操作的链接?

【问题讨论】:

    标签: ruby-on-rails forms link-to


    【解决方案1】:

    默认情况下,表单按钮将具有提交类型。您需要指定按钮类型。

    尝试以下方法:

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

    【讨论】:

    • 有没有办法在表单中使用 ruby​​ 标签来做到这一点?例如:&lt;%= f.button "Next", class: "btn btn-theme", id: "btn-next" %&gt;
    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2018-09-15
    • 2019-11-29
    • 2014-03-15
    相关资源
    最近更新 更多