I have this line of code in a User model:
attr_accessor :birthdate
In the same model, I have a method that tries to set that birthdate by doing this:
self.birthdate = mydate
Where mydate is a Date object.
I get this error: undefined method birthdate='
Why is this happening? Isn't attr_accessor creates a setter and a getter?
Let me guess, you're calling that setter from a class method, right?
class Foo
attr_accessor :bar
def set_bar val
self.bar = val # `self` is an instance of Foo, it has `bar=` method
bar
end
def self.set_bar val
self.bar = val # here `self` is Foo class object, it does NOT have `bar=`
bar
end
end
f = Foo.new
f.set_bar 1 # => 1
Foo.set_bar 2 # =>
# ~> -:10:in `set_bar': undefined method `bar=' for Foo:Class (NoMethodError)
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