Skip to content

Instantly share code, notes, and snippets.

@searls
Created January 7, 2024 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searls/cae7aa2b0882f315cc7b73c04bdfcabd to your computer and use it in GitHub Desktop.
Save searls/cae7aa2b0882f315cc7b73c04bdfcabd to your computer and use it in GitHub Desktop.
Abbreviated example code that was exhibiting an N+1 only for non-image (video/pdf) preview representations
class FeedsController < ApplicationController
def index
@posts = Post.with_visuals.order(published_at: :desc)
end
end
<div class="flex">
<% @posts.each do |post| %>
<%= link_to feed_post_path(post, post.web_path) do %>
<%= image_tag "https://#{ENV["CDN_HOST"]}/#{post.preview_image.key}" %>
<% end %>
<% end %>
</div>
class Post < ApplicationRecord
belongs_to :user
has_many :visuals, -> { order(position: :asc) }, dependent: :destroy
accepts_nested_attributes_for :visuals, allow_destroy: true, limit: 10
def self.with_visuals
includes(:visuals).merge(Visual.with_attached_file)
end
def preview_image
visuals.first.file.representation(:preview)
end
end
class Visual < ApplicationRecord
belongs_to :post
has_one_attached :file, dependent: :purge_later do |attachable|
attachable.variant :preview, resize_to_fill: [200, 200], preprocessed: true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment