1

I am trying to update two attributes in a method like this:

def my_method
  @from = @to = Time.zone.now
end

but when I call this method I don't get set values in from and to:

my_model.from => nil
my_model.to   => nil

with this it works:

self.from = self.to = Time.zone.now

my_model.from => Sat, 20 Jul 2013 20:54:40 UTC 00:00
  1. do you know why the first way does not work?
  2. could you give me some advice about the difference between these? how are they called? instance vars or attr_accessors? actually I need help defining this second question.

Update

from and to are persisted attributes

sites
  • 21,417
  • 17
  • 87
  • 146

2 Answers2

1

Persisted attributes are not simple attributes/instance variables.

They are managed by ActiveRecord and you must use the self.xxx when setting them.

When reading them, e.g., obj.from, it's calling the accessor added by active record.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • When I use `obj.from` with `attr_accessor` there is an instance variable `@from` in `obj`, right? so in this case ActiveRecord accessor does not define such instance variable, right? any link to read how this works? – sites Jul 20 '13 at 22:22
  • @juanpastas Correct; `attr_accessor` creates getter and setter methods. Persisted AR properties use DB properties to create those same methods, and they don't use instance variables, IIRC it's a hash but I'd have to look it up. I don't recall the best reference for all this at the moment, I'm sorry. – Dave Newton Jul 20 '13 at 22:33
-1
class Foo
  attr_reader :from, :to

  def my_method
    @from = @to = Time.now
  end
end

foo = Foo.new()
foo.my_method
puts foo.from  # => 2013-07-20 17:06:51 -0400
puts foo.to    # => 2013-07-20 17:06:51 -0400
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
  • will this present conflict with from to which are persisted attributes, any link to read how this works? – sites Jul 20 '13 at 21:39
  • 1
    @MichaelSzyndel In fairness, it was not originally clear from the OP's post what precisely they were doing, hence my clarifying comment. – Dave Newton Jul 20 '13 at 22:32