Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Attr accessor undefined method in the setter

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?

like image 393
Hommer Smith Avatar asked Dec 02 '22 23:12

Hommer Smith


1 Answers

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)
like image 195
Sergio Tulentsev Avatar answered Dec 08 '22 00:12

Sergio Tulentsev