Automaticaly update ActiveRecord object

Posted by Aleksandr Koss on Stack Overflow See other posts from Stack Overflow or by Aleksandr Koss
Published on 2010-03-30T08:13:17Z Indexed on 2010/03/30 8:23 UTC
Read the original article Hit count: 276

Filed under:

I have same models:

class Father < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :father
end

Then do something like that:

$ script/console test
Loading test environment (Rails 2.3.5)
>> @f1 = Father.create :test => "Father"
=> #<Father id: 1, test: "Father", created_at: "2010-03-30 08:01:41", updated_at: "2010-03-30 08:01:41">
>> @f2 = Father.find :first
=> #<Father id: 1, test: "Father", created_at: "2010-03-30 08:01:41", updated_at: "2010-03-30 08:01:41">
>> @f1 == @f2
=> true
>> @f1.children
=> []
>> @f2.children
=> []
>> @f1.children.create :test => "Child1"
=> #<Child id: 1, test: "Child1", father_id: 1, created_at: "2010-03-30 08:02:15", updated_at: "2010-03-30 08:02:15">
>> @f1.children
=> [#<Child id: 1, test: "Child1", father_id: 1, created_at: "2010-03-30 08:02:15", updated_at: "2010-03-30 08:02:15">]
>> @f2.children
=> []
>> @f2.reload
=> #<Father id: 1, test: "Father", created_at: "2010-03-30 08:01:41", updated_at: "2010-03-30 08:01:41">
>> @f2.children
=> [#<Child id: 1, test: "Child1", father_id: 1, created_at: "2010-03-30 08:02:15", updated_at: "2010-03-30 08:02:15">]

As you see rails cache @f2 object. To get actual data we should call reload.

There is a way to automatically reload @f2 after children update without calling method "reload"?

© Stack Overflow or respective owner

Related posts about rails