Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kwent/050b0a580fa635e5aaa225ea3a1dd846 to your computer and use it in GitHub Desktop.
Save kwent/050b0a580fa635e5aaa225ea3a1dd846 to your computer and use it in GitHub Desktop.
Rails | Active Storage Attachment + acts_as_list
# 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
# 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
User.first.sorted_images.last.update(position: 1)
# 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
@dancallaghan
Copy link

If using on multiple models/attachments the scope should be:

acts_as_list scope: %i[record_id record_type name]

@dancallaghan
Copy link

Also, just a side note: replacing has_many_attached with has_many removes a lot of dynamic methods. The has_many should also be scoped by the name of the attachment.

has_many :sorted_images, -> { where(name: "images").order(position: :asc) }, class_name: "ActiveStorage::Attachment", as: :record, inverse_of: :record, dependent: false

@senorlocksmith
Copy link

Was there any other sort of JavaScript used? I have been attempting something of the sort and cannot get the ajax or JavaScript to connect the position to the database. I can retrieve the position just not update the new position when moved.

@sbouchaala
Copy link

Instead of rewriting that has_many just to set order, you can simply set default_scope and let original has_many_attached in model:

module ActiveStorageAttachmentList
  extend ActiveSupport::Concern

  included do
    acts_as_list scope: %i[record_id record_type name]
    default_scope { order(:position) }
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment