ActiveStorage has_many_attached 附件排序


给class 增加 has_many_attached images,相当于是给class增加了下面的关系
  class Post < ApplicationRecord
     has_many :image_attachments, -> { where(name: 'image') }, class_name: "ActiveStorage::Attachment", as: :record, inverse_of: :record, dependent: false
     has_many :image_blobs, through: :image_attachments, class_name: "ActiveStorage::Blob", source: :blob
  end

This means we can leverage the relationship to handle sorting by filename which is actually an attribute of the ActiveStorage::Blob rather than the attachment. To do this we reference to the relation defined in by the macro images in your case and then join to its natural relationship to the ActiveStorage::Blob so that we can sort based on these fields.
The final result would be
   <% @post.images.joins(:blobs).order('active_storage_blobs.filename ASC').each do |image| %>

Now all of the images will be sorted by the filename however since joins does not actually load any data and I am assuming you are referencing the the file name in your view we could also use
   <% @post.images.includes(:blobs).references(:blobs).order('active_storage_blobs.filename ASC').each do |image| %>

To have a single query that loads the images and the ActiveStorage::Blob data all at once to avoid the n + 1 issues that could arise from the original version.


阅读量: 484
发布于:
修改于: