Clearing the Rails Query Cache
At Lovetastic (a relationship-focused personals site for gay men), we have an nifty feature that allows a user to undergo an “interview.” This section of our dating profiles encourages members to click a button and get new random questions added to their profile one at a time (answering the ones they like), making each set of profile questions unique to that user.
Because we don’t want to pose the same question twice, we check to see that the randomly-selected question hasn’t already been answered. If it has, we keep trying to find a random question until we find one that hasn’t been answered yet.
To express this logic in Ruby code:
@random_interview_question = Question.get_a_random_interview_question while @interview_answers.any? { |a| a.question == @random_interview_question } do @random_interview_question = Question.get_a_random_interview_question end
This has been working fine, of course, until the latest addition of query caching by default into Rails Edge.
Naturally, caching and randomness don’t get along very well.
Although undocumented, the way around this is simple:
Question.query_cache.clear_query_cache