Rails + Simple Form - 创建带有两个按钮的表单?

问题描述 投票:0回答:2

我正在尝试创建一个带有两个按钮的表单。其中一个是

submit
按钮,但我还希望有第二个按钮,允许创建表单所需的元素(如果该元素尚不存在)。

类似这样的:

<%= simple_form_for @class do |f| %>
  <%= f.input :title %>
  <%= f.association :teacher %>
  <%= f.button :new_teacher, new_teacher_path, "Add a Teacher" %>
  <%= f.button :submit %>
<% end %>

单击

:new_teacher
按钮时我想要发生的是打开新的教师视图,然后用户填写该视图,提交它,然后返回创建课程。有没有明智的方法来做到这一点?

这主要是一个设计问题,感觉按钮应该位于表单“内部”,这样,如果用户在填写表单时遇到缺少的项目,他/她可以轻松创建它。

ruby-on-rails simple-form
2个回答
3
投票

我发现的一个解决方案是使用

link_to
帮助器,并将链接样式设置为按钮。像这样:

<%= link_to 'Add a Teacher', new_teacher_path, :class => 'button' %>

我尝试使用

button_to
而不是
link_to
,看来 Simple Form 足够聪明,能够注意到这一点并假设按钮应该在表单的上下文中操作,所以我没有得到我想要的路径。


0
投票

它与此并不完全相关,但它可能会帮助那些正在寻找如何使用按钮发送请求(包括参数)的选项的人。为了清楚起见,让我们对此进行分解。我们将介绍默认请求类型以及如何在 Rails 中修改它,无论是版本 5 之前还是之后

Rails 5 之前

默认请求类型:HTML

发送 HTML 请求:

  1. 表格:

    <%= form_for @post do |f| %>
      <!-- form elements here -->
    <% end %>
    

    默认行为,作为 HTML 请求提交。

  2. 按钮

    <%= button_to "View Detail", movie_detail_path, method: :get, params: { movie_id: movie['id'] } %>
    

    作为 HTML 请求提交。

  3. 链接

    <%= link_to "View Details", movie_detail_path(movie_id: movie['id']) %>
    

    表现为标准链接(HTML GET 请求)。

发送 JSON 请求:

  1. 表格:

    <%= form_for @post, remote: true do |f| %>
      <!-- form elements here -->
    <% end %>
    

    使用Ajax提交(可以处理JSON响应)。

  2. 按钮

    <%= button_to "View Detail", movie_detail_path(format: :json), method: :get, params: { movie_id: movie['id'] }, remote: true %>
    

    指定 JSON 格式并使用 Ajax。

  3. 链接

    <%= link_to "View Details", movie_detail_path(movie_id: movie['id'], format: :json), remote: true %>
    

    指定 JSON 格式并发出 Ajax 请求。

Rails 5 之后

默认请求类型:JavaScript (Ajax)

发送 HTML 请求:

  1. 表格:

    <%= form_with model: @post, local: true do |f| %>
      <!-- form elements here -->
    <% end %>
    

    指定

    local: true
    以 HTML 形式提交。

  2. 按钮

    <%= button_to "View Detail", movie_detail_path, method: :get, params: { movie_id: movie['id'] }, local: true %>
    

    指定

    local: true
    用于 HTML 提交。

  3. 链接

    <%= link_to "View Details", movie_detail_path(movie_id: movie['id']) %>
    

    表现为标准链接(HTML GET 请求)。

发送 JSON 请求:

  1. 表格:

    <%= form_with model: @post do |f| %>
      <!-- form elements here -->
    <% end %>
    

    默认行为,作为 Ajax 请求提交(可以处理 JSON 响应)。

  2. 按钮

    <%= button_to "View Detail", movie_detail_path(format: :json), method: :get, params: { movie_id: movie['id'] } %>
    

    指定JSON格式,默认Ajax提交。

  3. 链接

    <%= link_to "View Details", movie_detail_path(movie_id: movie['id'], format: :json) %>
    

    指定 JSON 格式,标准链接行为。

© www.soinside.com 2019 - 2024. All rights reserved.