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

问题描述

这个让我发疯...

我有一个 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" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["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" = $1 LIMIT $2  [["id",8],1]]
  ↳ app/controllers/campaigns_controller.rb:93
Unpermitted parameters: :utf8,:commit

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

解决方法

我认为您想要实现的目标是:

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

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

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

说明

请看...当您向表单声明模型/范围时,Rails 会将这些参数与模型/范围名称嵌套在一起。

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...