gpt4 book ai didi

ruby-on-rails-3 - Rails 3 & Strong Parameters,获取质量分配错误

转载 作者:行者123 更新时间:2023-12-02 02:03:05 25 4
gpt4 key购买 nike

我正在尝试在我的 Rails 3 项目中的单个模型中使用强参数,该项目有大约 40-50 个模型。

我已经完成了以下操作,但是当我尝试创建或更新此模型的实例时,我遇到了关于质量分配的相同错误,如下所示,它显示了模型的每个字段。

我已经尝试从模型中删除 accepted_nested_attributes_for 并重新启动网络服务器,但这对我收到的错误没有影响。

config/application.rb

config.active_record.whitelist_attributes = false

app/models/my_service.rb(为了简洁而串联)

class CallService < ActiveRecord::Base

include ActiveModel::ForbiddenAttributesProtection

belongs_to :account
has_many :my_service_chargeables
accepts_nested_attributes_for :my_forward_schedules, allow_destroy: true


validates :start_date, :username, :account_id, :plan_id, presence: true
audited associated_with: :account

scope :enabled, where(enabled: true)
scope :within, lambda{|month| where(start_date: (month.beginning_of_month..month.end_of_month))}

end

app/controllers/my_services_controller.rb

def update
@my_service = MyService.find(params[:id])
if @my_service.update_attributes(permitted_params.my_service)
flash[:success] = "Service Updated"
redirect_to @my_service
else
render 'edit'
end
end

app/controllers/application_controller.rb

def permitted_params
@permitted_params ||= PermittedParams.new(current_user, params)
end

app/models/permitted_pa​​rams.rb

class PermittedParams < Struct.new(:user, :params)
def my_service
if user && user.role?(:customer)
params.require(:my_service).permit(*service_customer_attributes)
else
params.require(:my_service).permit!
end
end

def service_customer_attributes
[:timeout, :pin, :day]
end
end

更新时出错

ActiveModel::MassAssignmentSecurity::Error in MyServicesController#update

Can't mass-assign protected attributes: account_id, plan_id, start_date, username

我已经运行了一个调试器来确认代码命中了 PermittedParams 类的 params.require(:my_service).permit! 行,但是这个异常仍然存在被抛出,据我所知,应该没有什么导致这个模型需要将属性声明为 attr_accessible 的。

任何人都可以阐明这种行为吗?

我正在使用 gem 版本(来 self 的 Gemfile.lock):

strong_parameters (0.2.0)
rails (3.2.11)

最佳答案

我不确定你的确切用例是什么,但是做 params.require(:my_service).permit! 在这里似乎仍然是个坏主意,至少有人仍然可以覆盖你模型的PK。而不是 params.require(:my_service).permit! 为什么不这样做:

params.require(:my_service).permit(:timeout, :pin, :day, :account_id,
:plan_id, :start_date, :username)

或者将它们保存在另一个数组中并将它们与您现有的 service_customer_attributes 合并以保持其 DRY。

这将解决您的批量分配错误,并且会更加安全和明确。

关于ruby-on-rails-3 - Rails 3 & Strong Parameters,获取质量分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com