Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add another gotcha about preloading ActiveStorage variants #70

Merged
merged 1 commit into from
Jan 9, 2024

Conversation

Galathius
Copy link

@Galathius Galathius commented Jan 8, 2024

The way how ActiveStorage::VariantWithRecord#record is implemented breaks auto-preloading Active Storage variants:

  @record ||= if blob.variant_records.loaded? # <--- Here is the issue, association is not preloaded yet - so `find_by` is used
    blob.variant_records.find { |v| v.variation_digest == variation.digest }
  else
    blob.variant_records.find_by(variation_digest: variation.digest)
  end

To prevent n+1 you still need to use built-in Active Storage methods for preloading associations.

Examples:

User.with_attached_avatar.find(100).map { _1.avatar.variant(:small).processed.url }

or

message.images.with_all_variant_records.map do |file|
  file.representation(resize_to_limit: [100, 100]).processed.url
end

@Galathius Galathius force-pushed the master branch 2 times, most recently from 0050d8a to 34c5ca6 Compare January 8, 2024 23:23
Copy link
Owner

@DmitryTsepelev DmitryTsepelev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, thank you!

@DmitryTsepelev DmitryTsepelev merged commit eca3514 into DmitryTsepelev:master Jan 9, 2024
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants