【发布时间】:2013-05-01 12:26:12
【问题描述】:
我试图在我的 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_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
我已经运行了一个调试器来确认代码命中了PermittedParams 类中的params.require(:my_service).permit! 行,但是这个异常仍然不断被抛出,据我所知,应该没有什么导致这个模型需要将属性声明为 attr_accessible 的。
谁能解释一下这种行为?
我正在使用 gem 版本(来自我的 Gemfile.lock):
strong_parameters (0.2.0)
rails (3.2.11)
【问题讨论】:
-
只是出于兴趣,您有没有想过将
attr_accessible :account_id, :plan_id, :start_date, :username添加到您的模型中。我知道你知道这个错误Can't mass-assign protected attributes通常是什么意思。通过使用attr_accessible,它需要一个可访问的属性列表。所有其他属性都将受到保护。可能还想阅读一下 - guides.rubyonrails.org/security.html#mass-assignment -
这会破坏使用强参数 gem 的目的,因为它的目的是保护用户可以通过控制器设置哪些属性。
标签: ruby-on-rails-3 strong-parameters