html - Rails - 使用一个提交按钮提交多个表单

标签 html ruby-on-rails forms ruby-on-rails-4

在我的应用程序中,我有一个用于编辑所有用户的页面,但是我希望这样我只需单击一个提交按钮即可更新用户的详细信息,但目前我只能编辑一个用户并单击“更新用户” ' 按钮更改该用户的详细信息。

_form.html.erb

<%= form_tag edit_user_path do |form| %>
  <% @users.each do |user| %>
    <%= form_for user do |f| %>
      <% if @user.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
          <ul>
          <% @user.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
          </ul>
        </div>
      <% end %>
      <div class="field">
        <%= f.label :username %><br>
        <%= f.text_field :username %>
      </div>
      <div class="field">
        <%= f.label :sunday %><br>
        <%= f.text_field :sunday %>
      </div>
      <div class="field">
        <%= f.label :monday %><br>
        <%= f.text_field :monday %>
      </div>
      <div class="field">
        <%= f.label :tuesday %><br>
        <%= f.text_field :tuesday %>
      </div>
      <div class="field">
        <%= f.label :wednesday %><br>
        <%= f.text_field :wednesday %>
      </div>
      <div class="field">
        <%= f.label :thursday %><br>
        <%= f.text_field :thursday %>
      </div>
      <div class="field">
        <%= f.label :friday %><br>
        <%= f.text_field :friday %>
      </div>
      <div class="field">
        <%= f.label :saturday %><br>
        <%= f.text_field :saturday %>
      </div>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>
  <% end %>
  <%= submit_tag "Submit" %>
<% end %>

正如您所看到的,代码底部的 submit_tag 绝对不执行任何操作,但我希望它更新所有用户的详细信息。任何帮助将不胜感激!

最佳答案

反对:

<%= form_for user do |f| %>

用途:

<%= fields_for "users[]", user do |f| %>

之后,您将获得每个 user_id 的 Controller 参数值:

"users"=>{"user_id1"=>{"attr1"=>"value1"}, "user_id2"=>{"attr1"=>"value1"}

为了使更新对象集合成为可能,一种方法是向 UsersController 添加一个操作,如下所示:

def update_collection
  # Update users here
end

并更新config/routes.rb中的路由:

resources :users do
  collection do
    match 'update_collection',  via: [:put, :patch]
  end
end

并在主表单中使用正确的网址:

<%= form_tag update_collection_users_path, method: :put do |form| %>

关于html - Rails - 使用一个提交按钮提交多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557033/

相关文章:

javascript - 我希望点击文本框后 div 内容消失

iphone - 如何调试未收到 Apple 推送通知的问题?

ruby-on-rails - 自定义 JSON 输出

php - 如何在 php 中使用 preg_match?

vba - VBA中表格宽度和高度的单位是什么?

javascript - 使用 AJAX 提交所有表单数据

html - 在 Div 中真正居中文本

html - 对于只有一个可能取值的 HTML 属性,是否可以省略取值?

html - 当方向为行时,如何删除 FlexBox 子项的高度?

javascript - 排除 Rails 部署的 Heroku ExecJS 程序错误