How to get database data by disabling the Ruby on Rails cache system for only one case?

I am using Ruby on Rails v3.2.2, and I would like to get database data by disabling the system cache only in case. That is, in my view file, I have something like the following:

<h1>Random articles 1</h1>
<%= Article.order('RAND()').limit(3).inspect %>
...
<h1>Random articles 2</h1>
<%= Article.order('RAND()').limit(3).inspect %>

When a view file is displayed, it displays the same data for both in the "Random Articles 1" and "Random Articles 2" sections. This is because the Ruby on Rails cache system (default) / "convention") tries to hit the database as little as possible for performance reasons.

How can I prevent this behavior (only for the explanation described above), so to output different data for the search methods in my view file?

+3
source share
2 answers

ActiveRecord has a method uncached. It looks like you can use it like this:

articles = Article.uncached do
  Article.order('RAND()').limit(3)
end

but it’s better to extract this into the class method of your model.

See this article for more details.

+6
source

I tried to reproduce your problem, but failed (Rails 3.2.2, too, using the sqlite3 adapter, code below). But try this anyway:

Article.uncached do Article.order('RAND()').limit(3).inspect end

The following is an example of how I tried to reproduce your problem in an empty Rails project; for me, this still led the articles in a different order:

ActiveRecord::Migration.create_table :articles do |t| t.string :name end
class Article < ActiveRecord::Base; end
20.times do |i| Article.create :name => "Article#{i}" end
# sqlite doesn't have a RAND() function, emulate it
Article.connection.instance_variable_get(:@connection).define_function 'RAND' do rand end
p *Article.order('RAND()').limit(3)

You may have noticed a mistake in the way I tried to reproduce your problem.

0
source

All Articles