【发布时间】:2020-05-01 20:19:07
【问题描述】:
当我将所有属性添加到必要的函数并在正确的位置引用它(据我所知)时,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
参数函数:
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
【问题讨论】:
-
你能发布你的 ShipmentMethod 类吗?我在日志中看到用户模型正在加载 id 5,这是 current_user 值吗? ShipmentMethod 是否依赖于用户?这里的模型上是否有 before_save 或其他一些回调会触及用户并验证某些内容?我怀疑它可能与某些依赖项有关。
-
发布类-我相信用户模型加载了由于页面的cancancan授权,但我会调查它。
-
抱歉 - 我指的是 ShipmentMethod 模型本身 - 而不是控制器。
-
模型发布,不知道我在想什么!这正在煎熬我可怜的大脑。注释掉 create 方法中的所有内容会导致相同的错误,因此我正在管道中的其他地方进行搜索。
-
ForbiddenAttributesError:行之后的日志中有更多详细信息吗?我希望有更多的细节可能会有所帮助......
标签: ruby-on-rails ruby strong-parameters