views:

19

answers:

1

I have a problem with making changes to an object from within another model as well as within the object's model. I have the following models:

class Foo < ActiveRecord::Base
  has_many :bars

  def do_something
    self.value -= 1
    # Complicated code doing other things to this Foo

    bars[0].do_other

    save!
  end
end

class Bar < ActiveRecord::Base
  belongs_to :foo

  def do_other
    foo.value += 2
    foo.save!
  end
end

If I have a Foo object with value set to 1, and call do_something on it, I can see from my database logs the following two operations:

Foo Update (0.0s) UPDATE "foos" SET "value" = 2 WHERE "id" = 1
Foo Update (0.0s) UPDATE "foos" SET "value" = 0 WHERE "id" = 1

... so do_something is presumably caching the self object. Can I avoid this, other than by moving the save!s around?

+1  A: 
John Topley
What are associations in this context? Also, if I reload the object, does that override any local unsaved changes?
Chris
Apparently not. Ok, this works - although I'm still not sure to what association refers.
Chris
Ah, brain fade. It's the has_many, belongs_to decorator, isn't it?
Chris
@Chris that's right.
John Topley