Rails: Attr accessor undefined method in the setter

attr-accessor, ruby, ruby-on-rails, setter

Solution

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)

Problem

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?

Original source