Caching ActionText Attachments

I am currently writing a Rails app in which users can create articles and reference them between eachother. Since these references also need to be shown when the article it references doesn’t exist (through a user settable ‘page id’) I chose to go with creating a custom ephemeral model:

class PageLink
  include ActionText::Attachable
  include GlobalID::Identification
  include ActiveModel::Model

  attr_accessor :campaign_id, :page_id, :article

  delegate :cache_key, to: :article

  def self.find(id)
    campaign_id, page_id = id.split(";")
    PageLink.new(campaign_id, page_id)
  end

  def initialize(campaign, page_id)
    @campaign_id = campaign
    @page_id = page_id
    @article = Article.find_by_page_id_and_campaign_id(@page_id, @campaign_id)
  end

  def id
    "#{@campaign_id};#{@page_id}"
  end

  def article_exists?
    @article.present?
  end

  def to_trix_content_attachment_partial_path
    "page_links/page_link"
  end
end

I then simply check if the given @article exists or not and render a ‘create now’ link if it does not. Now, my issue is that if a user has a lot of these references to the same page then it still takes several 100s of milliseconds to render them. The SQL queries for the article itself do get cached, but since accessing the cache is not free either it adds some delay I’d rather avoid.

Now, the all have the same sgid, so I was wondering if there would be a way to make ActionText realize that having the same sgid should render them the same and only try to ‘render’ once and insert it for each reference.

Thank you for any pointers!


PS: Here’s how the timing looks like:

image

Can you add a cache statement in your page_links/page_link partial?

Thanks for the pointer! So, I was already caching but ofc it is not being cached in dev unless one enables it (with rails dev:cache). With that, it has gotten better but it is still too slow for my taste:

I assume that it does template resolution etc for every attachment which just adds up.

Similarly, could you wrap your rich_text_area statement into a cache?

1 Like

Heh, yeah that would work. The problem with this much caching is that it makes invalidating the cache much more difficult. Since the page_link itself needs the title of the article it is referencing I’d need a way to signal this to the cache.

I believe the best place to cache this is at the ActionText level, where if it seems attachments with the same SGID it should just use the cache, which would alleviate this issue.