在Active Storage Rails 5.2中按文件名订购多个图像

时间:2019-04-05 16:11:42

标签: ruby-on-rails rails-activestorage

我在Post模型中具有has_many_attached图片关系。我想在“发布秀”页面上显示图像时按其文件名排序。如何按文件名排序?

示例:

<% @post.images.order("id DESC").each do |image| %>

是否可以通过诸如active_storage_blob.filename之类的文件名按文件名排序?

3 个答案:

答案 0 :(得分:2)

我需要Rails 6

@post.images.includes(:blob).references(:blob).order('active_storage_blobs.filename ASC').each do |image|
  # ...
end

答案 1 :(得分:0)

When you add the has_many_attached macro to a class it actually adds the following relationships to your 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.

答案 2 :(得分:0)

如果您使用ActiveStorage设置了类,例如:

class Post < ApplicationRecord
  has_many_attached :images
end

您可以运行此命令来排序并避免N + 1个查询

@post.images.includes(:blob).references(:blob).order(:filename)