开发者

Clearing ActiveRecord cache

I'm building a command line application using ActiveRecord 3.0 (without rails). How do I clear the query ca开发者_如何转开发che that ActiveRecord maintains?


To a first approximation:

ActiveRecord::Base.connection.query_cache.clear


Have a look at the method clear_query_cache in http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/QueryCache.html


We use:

ActiveRecord::Base.connection.query_cache.clear
(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|
  table.classify.constantize.reset_column_information rescue nil
end

But I am not certain even this is enough.


If you only want to do this temporarily, you can use ActiveRecord::Base.uncached like so:

::ActiveRecord::Base.uncached { User.order('random()').limit(3) }


Oftentimes when you see caching of database queries, your db is doing the caching, not ActiveRecord, which means you need to clear the cache and buffers at the db level, not the ActiveRecord level.

For example, to clear Postgres' cache and buffers on Mac, you would do sudo purge, which forces the disk cache to be flushed and emptied.

To clear Postgres' cache and buffers on Linux, you would shut down postgres, drop the caches, and start postgres back up again:

service postgresql stop
sync
echo 3 > /proc/sys/vm/drop_caches
service postgresql start

Further reading:

  • See and clear Postgres caches/buffers?
  • Does Postgres provide a command to flush buffer cache?
  • https://linux-mm.org/Drop_Caches


Since, the title of the question is so broad, I stumbled over it while searching for a related problem: When adding columns to an ActiveRecord model during a migration, it may happen that the new column is not available on the ActiveRecord class. Rails caches the column information. In order to fix this we need to call reset_column_information.

Here and example:

# migration
Product.first # rails caches the schema

add_column :products, :name
Product.first.update(name: 'xxx') # fails

Product.reset_column_information
Product.first.update(name: 'xxx') # now it succeeds
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜