Last active
February 3, 2024 16:25
-
-
Save kwent/050b0a580fa635e5aaa225ea3a1dd846 to your computer and use it in GitHub Desktop.
Rails | Active Storage Attachment + acts_as_list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# db/migrate/20200119064500_add_position_column_to_active_storage_attachments.rb | |
class AddPositionColumnToActiveStorageAttachments < ActiveRecord::Migration[6.0] | |
def change | |
add_column :active_storage_attachments, :position, :integer, default: 0 | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/active_storage_attachment.rb | |
module ActiveStorageAttachmentList | |
extend ActiveSupport::Concern | |
included do | |
acts_as_list scope: [:record_id] | |
end | |
end | |
Rails.configuration.to_prepare do | |
ActiveStorage::Attachment.send :include, ActiveStorageAttachmentList | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User.first.sorted_images.last.update(position: 1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/user.rb | |
class User < ApplicationRecord | |
# Active Storage overrides to sort by position | |
has_many :sorted_images, -> { order(position: :asc) }, class_name: "ActiveStorage::Attachment", as: :record, inverse_of: :record, dependent: false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of rewriting that has_many just to set order, you can simply set
default_scope
and let originalhas_many_attached
in model: