Button_to 表单中的标签关闭表单

Button_to tag in a form closes form

我目前正在 rails 3 上使用 ruby 中的表单。因此,在我的项目表单中,我有一个按钮可以让用户退出该项目。然而,奇怪的是,button_to 标签关闭了我的整个表单,我不能再使用我的提交按钮了。

所以我尝试了很多,但我不明白为什么会这样。

这是我的表格:

<%= form_for @project, html: { class: "form-horizontal project" } do |f| %>
    <div>
          <%= f.label :users, 'Project Users:',  :class => 'control-label', style: 'margin-bottom: 20px' %>
          <div>
            <% @project.users.order('last_name').each do |user| %>
                      <div style="margin-bottom: 15px">
                        <%= user.name %>
                          <%= button_to 'Sign Out', sign_user_out_project_path(user_id: user.id, id: @project), method: :delete, class: 'btn btn-danger btn-xs pull-right', style:'margin-right: 600px; margin-top: -20px' %>
                      </div>
            <% end %>
          </div>
        </div>


      <%= f.submit nil, :class => 'btn btn-primary' %>
      <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                projects_path, :class => 'btn btn-default' %>

    <% end %>

在我看来,这段代码看起来不错,因为所有标签都已完全关闭。但是,我认为使用 button_to 时可能会有一些魔力,所以也许有人知道更好的方法来做我想做的事情。

谢谢!

不要在您的表单中放置 button_to

根据 docs:

(button_to) Generates a form containing a single button that submits to the URL created by the set of options

--

HTML 表单有一个 clear spec,无论何时实施表单,您都应该遵守这一点。

在表单中包含表单会导致 "outer" 表单停止工作(HTML 无法在 </form>.

之前处理另一个 <form>

简单的答案是从您的表单中删除您的 button_to 并将其放在外面,(在您的情况下),用另一个元素替换它(link_to).如果你想让 link 看起来像一个按钮,你可以使用 <button> markup 创建一个按钮:

<%= form_for @project, html: { class: "form-horizontal project" } do |f| %>
    <div>
          <%= f.label :users, 'Project Users:',  :class => 'control-label', style: 'margin-bottom: 20px' %>
          <div>
            <% @project.users.order('last_name').each do |user| %>
                      <div style="margin-bottom: 15px">
                        <%= user.name %>   
                        <%= link_to '<button>Sign Out</button>'.html_safe, sign_user_out_project_path(user_id: user.id, id: @project), method: :delete, class: 'btn btn-danger btn-xs pull-right', style:'margin-right: 600px; margin-top: -20px' %>
                      </div>
            <% end %>
          </div>
        </div>

      <%= f.submit nil, :class => 'btn btn-primary' %>
      <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                projects_path, :class => 'btn btn-default' %>

<% end %>