簡體   English   中英

如何更新rails 6中的多條記錄

[英]How to update multiple record in rails 6

我的 controller

class IndustryController < ApplicationController
  def index
      @industries=Industry.all
    end
    def new
      @industry=Industry.new
    end
    def create
      @industry = Industry.new(industry_params)
      # @industry = Industry.new(params[:name_bef,:name,:status])
      # @industry = Industry.new(:name_bef => (params[:name]),:name => (params[:name]), :status => (params[:status]))
      if @industry.save
        redirect_to industry_index_path
      else
        render 'new'
      end
    end

  def update 

    @industry = Industry.all

    @industry.each do |i|
      @industry.find(i.id)
      @industry.update(industry_params)
    end
  end
  private
  def industry_params
    params.require(:industry).permit(:name, :status)
  end

  private
  def industry_update
    params.require(:industry).permit(:name, :status)
  end

end

我的 html

<%= form_for @industries, as: :industry, url: industry_path(@industries), method: :patch do |f| %>
  <table class="table table-bordered">
    <thead class="bg-light">
      <tr>
        <th scope="col">業種名(変更前)</th>
        <th scope="col">業種名</th>
        <th scope="col">狀態</th>
      </tr>
      </thead>
      <tbody>
        <% @industries.each do |industry| %>
        <tr>
          <td><%= industry.name %></td>
          <td>
            <div class="form-group">
              <%= f.text_field :name, :value => industry.name, :id => industry.id, :class => "form-control" %>
            </div>
          </td>
          <td>

          </td>
        </tr>
        <% end %>
      </tbody>
    </table>
      <div class="form-group text-center">
        <%= f.submit"登録", :class => " btn btn-success" %>
      </div>
    <%end%>

我的假設是您正在談論 controller 中的update操作。 看起來update_all是您正在尋找的方法。

def update
  Industry.update_all(industry_params)
end

這可能很危險 - 請注意,這將繞過活動記錄驗證和回調,因此請確保您確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM