I have a controller action that calls a model method which generates a serialized list of data pulled from another model database. I need this to be uncached because the SQL queries should be random data pulls.
Here’s a general idea of my code (Note that User has_one Foo, Bar is an arbitrary model of data, :data_list is of type text, and the database is SQLite):
# app/models/foo.rb
class Foo < ActiveRecord::Base
serialize :data_list
def generate_data
list = []
for i in 1..4
data = Bar.find(:first, :order => "Random()")
list << data
end
self.data_list = list
end
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def generate_action
...
uncached do
@user.foo.generate_data
end
@user.foo.save
end
end
# app/views/user/show.html.erb
...
<% @user.foo.data_list.each do |data| %>
<%= data %><br />
<% end %>
Whenever uncached do ... end is removed, everything works fine and the show view prints out each set of Bar objects in @user.foo.data_list. Unfortunately, because of Rails’ SQL caching, it ends up look like this:
RandomDataPoint8
RandomDataPoint8
RandomDataPoint8
RandomDataPoint8
When I need to look like this:
RandomDataPoint7
RandomDataPoint13
RandomDataPoint2
RandomDataPoint21
It should be noted that running user.foo.generate_data from Rails command line works perfectly with the randomization. It is only when being called from the controller that caching starts to occur.
My research suggested I use uncached in the controller to remove caching, however it seems to destroy my data serialization and I receive the error:
undefined method 'each' for #<String:0x007ff49008dc70>
In fact, it does this even if I retroactively add in uncached (having successfully generated a data_plan without uncached prior) and save the controller, but don’t call generate_action.
EDIT
I believe this problem is actually related to the fact that I was storing an object in the hash. Switching to the object
idfixed this problem. Another SO question of mine regarding this can be found here:Rails – Accessing serialized data from console
The following has been preserved just because the syntax may still help people, but I don’t believe it was the actual cause of the problem.
I solved this by moving
uncachedto the model. For reference, the source I was using to originally solve this problem was this link: http://railspikes.com/2008/8/18/disabling-activerecord-query-caching-when-neededWhat I overlooked is that he puts
uncachedin the model, not the controller. Also, the syntax needed to be a little different:instead of
The source for the syntax correction is this SO response: https://stackoverflow.com/a/967690/337903