我想在我的Rails 3項目中使用強大的參數,在單個模型中有大約40-50個模型。Rails 3&強大的參數,獲得質量分配錯誤
我已經完成了以下工作,但是當我嘗試創建或更新此模型的一個實例時,我得到了關於質量分配的相同錯誤,如下所示,它顯示模型的每個字段。
我試着從模型中刪除accepted_nested_attributes_for
並重新啓動網絡服務器,但它對我收到的錯誤沒有影響。
配置/ application.rb中
config.active_record.whitelist_attributes = false
應用/模型/ 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
ERROR當更新
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's。
任何人都可以闡明這種行爲?
我使用的gem版本(從我Gemfile.lock的):
strong_parameters (0.2.0)
rails (3.2.11)
只是出於興趣,你沒有想過在你的模型中添加attr_accessible:account_id,:plan_id,:start_date,:username。正如我知道你知道這個錯誤「不能大規模分配受保護的屬性」通常意味着什麼。通過使用'attr_accessible',它將獲取一個可訪問的屬性列表。所有其他屬性將受到保護。也可能想在此閱讀 - http://guides.rubyonrails.org/security。html#mass-assignment – David 2013-05-02 00:17:03
這會破壞使用強參數gem的目的,因爲它意味着處理用戶可以通過控制器設置哪些屬性的保護。 – bdx 2013-05-02 07:49:16