Dec
9th
Sun
9th
ActiveRecord's QueryCache#uncache
Sometimes you need to compare an attribute of an in-memory ActiveRecord instance against its attribute in the database. The way I usually do that is to grab a fresh instance from the database like this:
class Something < ActiveRecord::Base
def previous(attribute)
self.class.find(id)[attribute]
end
end
That worked just fine in Rails 1.2. But Rails 2.0 has request-scoped query caching enabled by default, meaning that if you have already executed the same SQL that is generated by find(id), you’re going to get the exact same instance back from that call to find. This makes it impossible to compare in-memory attributes against attributes stored in the database.
The solution is to use ActiveRecord’s uncache method. This is a class method, so you’ll need to grab your class to call it like this:
class Something < ActiveRecord::Base
def previous(attribute)
self.class.uncached { self.class.find(id)[attribute] }
end
end