当我为必要的函数添加了所有属性并在正确的地方引用它时,Rails在尝试创建时抛出一个错误(据我所知)。可以成功地更新。不幸的是,它发生在多个控制器上。我假设所有控制器的问题都是一样的。
这是升级到rails 5的一部分,之前是rails 2。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
Params函数:
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 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_params
和 update_params
如果你对这些动作有不同的参数。