我试图在我的 Rails 3 项目中的单个模型中使用强参数,该项目有大约 40-50 个模型。
我已经完成了以下操作,但是当我尝试创建或更新此模型的实例时,我收到关于质量分配的相同错误,如下所示,它显示了模型的每个字段。
我已经尝试accepted_nested_attributes_for
从模型中删除并重新启动网络服务器,但它对我收到的错误没有影响。
配置/应用程序.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
应用程序/控制器/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
应用程序/控制器/application_controller.rb
def permitted_params
@permitted_params ||= PermittedParams.new(current_user, params)
end
应用程序/模型/permitted_params.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
我已经运行了一个调试器来确认代码命中了类中的params.require(:my_service).permit!
行PermittedParams
,但是这个异常仍然不断被抛出,据我所知,应该没有什么导致这个模型需要将属性声明为 attr_accessible 的。
任何人都可以阐明这种行为吗?
我正在使用 gem 版本(来自我的Gemfile.lock):
strong_parameters (0.2.0)
rails (3.2.11)