【问题标题】:Rails 3.2 - Why am I getting mass-assign protection error despite using .save(validate: false)?Rails 3.2 - 尽管使用 .save(validate: false),为什么我会收到大量分配保护错误?
【发布时间】:2014-11-04 00:16:59
【问题描述】:

我有一个Timesheet 模型,但它的许多属性都没有添加到attr_accessible。尝试在seeds.rb 中创建种子数据,但在运行rake db:seed 以及在控制台中尝试代码时(尽管使用了.save(validate: false))都会出现质量分配保护错误。

来自rake db:seed 的错误输出:

rake aborted!
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: spent, worked_time, driving_time

控制台:

pry(main)> ts = Timesheet.new(spent: 0, review: "none", driving_time: 0, worked_time: 3600).save(validate: false)
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: spent, driving_time, worked_time
from /home/vagrant/.rvm/gems/ruby-1.9.3-p547/gems/activemodel-3.2.18/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord mass-assignment


    【解决方案1】:

    您需要跳过批量分配,.save(validate: false) 只跳过验证。

    尝试传递选项:

    :without_protection => true
    

    你需要做的是:

    ts = Timesheet.new(spent: 0, review: "none", driving_time: 0, worked_time: 3600, :without_protection => true).save(validate: false)
    

    【讨论】:

      【解决方案2】:

      请试试这个:

      ts = Timesheet.new({spent: 0, review: "none", driving_time: 0, worked_time: 3600}, 
      without_protection: true).save(validate: false)
      

      更多信息here

      最佳实践表明,如果您希望您的用户在更新或创建表单时发送此数据,则必须将您希望用户在模型中更新的字段列入白名单attr_accessible :spent, :driving_time, :worked_time

      选项validate: false 阻止保存前的验证,但不阻止批量分配控制。

      【讨论】:

        猜你喜欢
        • 2012-05-19
        • 2022-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-24
        • 2014-04-25
        相关资源
        最近更新 更多