3

我试图在我的 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_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

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

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

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

strong_parameters (0.2.0)
rails (3.2.11)
4

1 回答 1

2

我不确定您的确切用例是什么,但是在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以保持干燥。

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

于 2013-05-16T15:43:10.020 回答