不允许的参数 utf8,更新操作中的方法

Unpermitted parameters utf8, method in update action

这个快把我逼疯了...

我有一个 form_for,我想为其更新一条 campaign 记录。

我在提交表单和更新活动时在日志中收到以下错误:

Unpermitted parameters: :utf8, :_method, :authenticity_token, :campaign, :commit

广告系列参数

def campaign_params
  params.permit(:box, :id, :name, :photo1, :delivery_date, :numberofitems, :extras, :card, :custom_message, :shipping_type, :totalitems, :companylogodesign, :companycarddesign,:selectedproducts => [])
end

我的路线:

resources :campaigns

我的表格:

<%= form_with(model: campaign, local: true) do |form| %>
  <% if campaign.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(campaign.errors.count, "error") %> prohibited this campaign from being saved:</h2>

      <ul>
      <% campaign.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <div class="field">
    <%= form.label :status %>
    <%= form.number_field :status %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

在我的控制器动作中,我有最简单的更新方法:

  def update
    respond_to do |format|
      if @campaign.update(campaign_params)
        format.html { redirect_to @campaign, notice: 'Campaign was successfully updated.' }
        format.json { render :show, status: :ok, location: @campaign }
      else
        format.html { render :edit }
        format.json { render json: @campaign.errors, status: :unprocessable_entity }
      end
    end
  end

错误日志:

Started PATCH "/campaigns/8" for ::1 at 2021-03-31 01:02:25 +0200
Processing by CampaignsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"6/k7vBdzh/PxeGFnzVcny2w23Tm1XUd2BnIB1X0l56fDQA1Psudlb3uKzp983ER4RUdJMayeRD88wANRl1k6GA==", "campaign"=>{"name"=>"sdsd", "status"=>""}, "commit"=>"Update Campaign", "id"=>"8"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  ORDER BY "users"."id" ASC LIMIT   [["id", 1], ["LIMIT", 1]]
  ↳ /Users/x/.rvm/gems/ruby-2.7.2/gems/activerecord-5.2.4.4/lib/active_record/log_subscriber.rb:98
  Campaign Load (0.2ms)  SELECT  "campaigns".* FROM "campaigns" WHERE "campaigns"."id" =  LIMIT   [["id", 8], ["LIMIT", 1]]
  ↳ app/controllers/campaigns_controller.rb:93
Unpermitted parameters: :utf8, :_method, :authenticity_token, :campaign, :commit

¿我错过了什么?非常感谢

我认为您要实现的目标类似于:

if @campaign.update(campaign_params.require(:campaign).permit!)

permit! 风险很大。所以我会这样做:

if @campaign.update(campaign_params.require(:campaign).permit(:name, :status))

说明

看...当您向表单声明 model/scope 时,Rails 将使用 model/scope 名称嵌套此参数。

所以您在表单中使用的参数嵌套在 campaign 键下。默认情况下,Rails 会发送一些额外的参数,您可能已经注意到(authenticity_tokencommitutf8 等)。

unpermitted params 错误意味着您不能使用这些参数来更新实体(出于安全原因),除非您明确声明它。