Skip to content

Instantly share code, notes, and snippets.

@Bighamster
Last active March 11, 2021 04:07
Show Gist options
  • Save Bighamster/70eae6cafb1b47f54d5d26127edd2e0d to your computer and use it in GitHub Desktop.
Save Bighamster/70eae6cafb1b47f54d5d26127edd2e0d to your computer and use it in GitHub Desktop.
Using a join model to annotate Active Storage blobs with custom data
Project.first.images.attach(io: File.open(filename), filename: filename, content_type: 'image/jpg')
class Image < ApplicationRecord
belongs_to :project
has_one_attached :file
delegate_missing_to :file
scope :positioned, -> { order(position: :asc) }
end
<% @projects.with_attached_images.each do |project| %>
<%# ... %>
<% end %>
class Project < ApplicationRecord
has_many :images, dependent: :destroy
scope :with_attached_images, -> { includes(:images).merge(Image.with_attached_file) }
end
<% @project.images.positioned.with_attached_file.each do |image| %>
<%= image_tag image %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment