Possible Duplicate:
attr_accessor default values
I am using Ruby on Rails 3.0.9 and I would like to initialize some attr_accessor
attribute values in my class\model that inherits from ActiveRecord::Base
. That is,
... in my module I have:
class User < ActiveRecord::Base
attr_accessor :attribute_name1,
:attribute_name2,
:attribute_name3,
...
end
and I would like to set to true
all attr_accessor
attribute values. How can I do that?
P.S.: Of course I would like to solve the above issue approaching "à la Ruby on Rails Way". I know about the after_initialize
callback but by using that method I should repeat each attribute_name<N>
statement for which I would like to set the value to true
inside that after_initialize
statement (... and this is not DRY - Don't Repeat Yourself). Maybe there is a better way to achieve this. Is there a way to set attr_accessor
attribute values "on the fly" when you state those attributes? That is, I expect to declare and set attr_accessor
attributes at once!
For Rails 3.2 or earlier, you could use attr_accessor_with_default
:
class User < ActiveRecord::Base
attr_accessor_with_default :attribute_name1, true
attr_accessor_with_default :attribute_name2, true
attr_accessor_with_default :attribute_name3, true
...
end
Since your default value is an immutable type (boolean), this form of the method is safe to use here. But don't use it if the default value is a mutable object, including an array or string, because all of your new model objects will share the exact same instance, which is probably not what you want.
Instead, attr_accessor_with_default
will accept a block, where you can return a new instance each time:
attr_accessor_with_default(:attribute_name) { FizzBuzz.new }
Did you try:
class User < ActiveRecord::Base
attr_accessor :attribute_name1,
:attribute_name2,
:attribute_name3,
...
after_initialize :set_attr
def set_attr
@attribute_name1 = true
...
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With