Rails 5 - 禁止属性

Rails 5 - Forbidden Attributes

当我将所有属性添加到必要的函数并在正确的位置引用它(据我所知)时,

Rails 在尝试创建时抛出错误。可以成功更新。不幸的是,它发生在多个控制器上。我想他们的问题都是一样的。

这是 rails5 升级的一部分,之前是 rails2。Ruby 版本:2.6.3

创建函数:

def create
    @shipment_method = ShipmentMethod.new(shipment_methods_params)
    respond_to do |format|
      if @shipment_method.save
        format.html { redirect_to shipment_methods_url, notice: 'Shipment method was successfully created.' }
        format.json { render json: @shipment_method, status: :created, location: @shipment_method }
      else
        format.html { render action: "new" }
        format.json { render json: @shipment_method.errors, status: :unprocessable_entity }
      end
    end
  end

参数函数:

def shipment_methods_params
    params.require(:shipment_method).permit(:name, :description, :shipping_url, :active, :supports_tracking, :requires_phone)
  end

请求参数:

Request parameters  
{"utf8"=>"✓", "authenticity_token"=>"KjPFsCA5xwgeIx4U3eOH4sA1IuYY5FSw6kvK16XyyKarEzlxSi6N04LFBdsJHWyIwt+ujv6gz9D+flYBeJ+pWA==", "shipment_method"=>{"name"=>"1", "description"=>"1", "shipping_url"=>"1", "active"=>"0", "supports_tracking"=>"0", "requires_phone"=>"0"}, "commit"=>"Create Shipment method", "controller"=>"shipment_methods", "action"=>"create"}

请求的服务器日志:

Processing by ShipmentMethodsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"KjPFsCA5xwgeIx4U3eOH4sA1IuYY5FSw6kvK16XyyKarEzlxSi6N04LFBdsJHWyIwt+ujv6gz9D+flYBeJ+pWA==", "shipment_method"=>{"name"=>"1", "description"=>"1", "shipping_url"=>"1", "active"=>"0", "supports_tracking"=>"0", "requires_phone"=>"0"}, "commit"=>"Create Shipment method"}
  User Load (0.6ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 5 ORDER BY `users`.`id` ASC LIMIT 1
Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.6ms)



ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError:

完整 class:

class ShipmentMethod < ActiveRecord::Base
  # public :description, :active, :name, :requires_phone, :supports_tracking, :shipping_url

  ## Associations
  has_many :shipments

  ## Validations
  validates :name, presence: true, uniqueness: true

  ## Scopes
  default_scope -> {order(:name)}
  scope :active, -> {where("active = 1")}
end

如果在您的控制器中有一个 load_and_authorize_resource 之前的操作,则发生的情况是该方法正在获取您的参数并尝试在它到达该方法之前创建一个实例。因此它会忽略您创建的强参数。

所以,当然,它永远不会到达方法和 BAM——可怕的 FAE

一种补救措施是调整之前的操作...

  load_and_authorize_resource :shipment_method, except: [:create]
  authorize_resource :shipment_method, only: [:create] 

但这很无聊

另一种是将强参数方法的名称更改为shipment_method_params...

def shipment_method_params
    params.require(:shipment_method).permit(:name, :description, :shipping_url, :active, :supports_tracking, :requires_phone)
  end

因为 Rails 及其对惯例的热爱。如果您对这些操作有不同的参数,您也可以单独制作 create_paramsupdate_params