Automaticaly update ActiveRecord object
- by Aleksandr Koss
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"?