This is a problem I had back in the Java Hibernate days as well, and I always wonder if I'm doing something wrong.
I frequently think of ActiveRecord as being magical (perhaps that's my first mistake), and what usually surprises me is when I have to explicitly reload an object to have a modification to the object be visible.
This often happens with callbacks, and in particular with association callbacks. If I thought it through I could probably figure it out, but...
So here's my current scenario. I have Article which has_many ArticleStatistics. There is an attribute Article#last_statistic_at which is the most recent datetime for any of an Article's ArticleStatistics.
I'm keeping it updated with a callback:
has_many :article_statistics, after_add: :update_article_last_statistic
def update_article_last_statistic article_statistic
article_statistic.update_article_last_statistic
end
and then in ArticleStatistic:
after_save :update_article_last_statistic
def update_article_last_statistic
article.update_attribute(:last_statistic_update,
self.statistic_at) if !article.nil? and
(article.last_statistic_update.nil? or (article.last_statistic_update < self.statistic_at))
end
In my spec, I have something like:
as = FactoryGirl.create(:article_statistic, statistic_at: t)
a.article_statistics << as
a.reload
a.should_not be_statistics_changed_in_last_hour
If I don't have that a.reload, the article (a) is stale.
I feel like I'm doing something wrong here...
Thanks --
Denis