Rails 5.2 Active Storage add custom attributes
If you need to store additional data with each image and perform queries based on that data, I’d recommend extracting an Image
model that wraps an attached file
:
# app/models/project.rb
class Project < ApplicationRecord
has_many :images, dependent: :destroy
end
# app/models/image.rb
class Image < ApplicationRecord
belongs_to :project
has_one_attached :file
delegate_missing_to :file
scope :positioned, -> { order(position: :asc) }
end
<%# app/views/projects/show.html.erb %>
<% @project.images.positioned.each do |image| %>
<%= image_tag image %>
<% end %>
Note that the example view above causes 2N+1 queries for a project with N images (one query for the project’s images, another for each image’s ActiveStorage::Attachment
record, and one more for each attached ActiveStorage::Blob
). I deliberately avoided optimizing the number of queries for clarity’s sake.