Refactoring and ActiveRecord Query + Russian Doll cache

The code should speak for itself:

module SomeHelper

  def user_has_access?
    if sales = current_user.sales.where(course_id:
      if sales.present?
        sales.last.access_expiration_date >


It’s a view helper to see if someone is a customer permitted access to a particular lesson. So there’s a Sales model, users can have many sales. And a Sale is associated with a course (and courses have many lessons) And there’s an expiration date, after which the user can’t view the content. This method would be used on a lessons#index, with some lessons being grayed out if the access isn’t allowed.

I feel like the above method is inefficient, but I can’t seem to figure out the correct refactor. It appears that there are two queries happening there, however I would like to get it to one.


if that’s inside of an .each do block and I’m using Russian doll - cache object do will it cache the result of the helper method? Meaning, how can I break the cache for something like that? Of course, I might not know what I’m talking about – I’ve never had helper methods inside a cache block before.

How would you guys solve this problem:

I want to display lessons for users who have a Sale and the Sale.access_expiration_date is still valid and I want to Russian doll the lessons#index (so as not to reload a hundred lessons every time the page is loaded) but ensure that when the expiration date happens, the user no longer has access to the lessons. The lessons will change very infrequently, so under normal circumstances, the cache isn’t likely to break (from a lesson change)