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

cu6pst1q  于 5个月前  发布在  Ruby
关注(0)|答案(2)|浏览(75)

我试图创建一个有两个按钮的表单。一个是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按钮被点击时,我希望新的教师视图打开,然后用户填写,提交它,然后返回创建类。有没有一种合理的方法来做到这一点?
这主要是一个设计问题,感觉按钮应该“在”表单中,这样如果用户在填写表单时遇到缺少的项目,他/她可以很容易地创建它。

vyswwuz2

vyswwuz21#

我发现的一个解决方案是使用link_to助手,将链接样式设置为按钮。像这样:

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

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

rslzwgfq

rslzwgfq2#

这与此并没有太大关系,但它可能会帮助那些正在寻找如何使用按钮发送请求的人,包括参数。为了清晰起见,让我们将其分解。我们将介绍默认的请求类型以及如何在Rails中修改它,包括版本5之前和之后
当然,这里有一个简化的之前之后Rails 5的细分:

Rails 5之前:
*默认请求类型:表单和按钮发送HTML请求。
*用于JSON请求:将remote: true添加到表单和按钮中,以使用Ajax发送JSON请求。
Rails 5之后:
*默认请求类型:表单和按钮默认使用JavaScript(Ajax)发送JSON请求。
*对于HTML请求:在表单和按钮中使用local: true切换回发送HTML请求。

Rails 5之前的示例

默认请求类型:HTML
发送HTML请求

1.形式

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

字符串
默认行为,作为HTML请求提交。
1.按钮

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


作为HTML请求提交。
1.友情链接

<%= 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响应)。
1.按钮

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


指定JSON格式并使用Ajax。
1.友情链接

<%= 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提交。
1.按钮

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


为HTML提交指定local: true
1.友情链接

<%= 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响应)。
1.按钮

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


指定JSON格式,默认Ajax提交。
1.友情链接

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


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

相关问题