【问题标题】:Rails 3 & Strong Parameters, getting mass assignment errorsRails 3 和强参数,得到质量分配错误
【发布时间】: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_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 版本(来自我的 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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多