LoginSignup
0
0

More than 5 years have passed since last update.

default_value_for + protected_attributesでmass assignment roleがおかしい

Last updated at Posted at 2013-09-21
class Test < ActiveRecord::Base
  attr_accessor :sample
  default_value_for :sample, true
  attr_accessible :sample, as: :admin
end

とすると、


Test.new({sample: false}, as: :admin)

で、
WARNING: Can't mass-assign protected attributes for ...
となる。

default_value_forを使わずに、after_initializeで対応すると成功した。


class Test < ActiveRecord::Base
  attr_accessor :sample
  attr_accessible :sample, as: :admin
  after_initialize :initialize_defaults
  def initialize_defaults
    self.sample = true if self.sample.nil?
  end
end

原因は、
default_value_forInstanceMethods::initializeを再定義してActiveRecord::Baseextendさせていることと、protected_attributesActiveRecord::MassAssignmentSecurity::Coreinitializeを再定義しており、ActiveRecord::Baseincludeさせていることが、競合していることだと思う。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0