Created
January 7, 2024 15:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FeedsController < ApplicationController | |
def index | |
@posts = Post.with_visuals.order(published_at: :desc) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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