Tomas Valent

Joined

10 Experience
0 Lessons Completed
0 Questions Solved

Activity

Add an Array/JSON Array type column to the model which declares the has_many_attached and store ids of ActiveStorage::Attachments in it. Then you can do :

# app/models/entry.rb
class Entry < ApplicationRecord
  has_many_attached :pictures


  def ordered_pictures
    pictures.sort_by{ |pic| ordered_picture_ids.index(pic.id) || (pic.id*100) }
  end

  def ordered_picture_ids=(ids)
    super(ids.map(&:to_i)) # convert any ids passed to this method to integer
                           # this is just for security reasons,
                           # you don't need to do this for the feature to work
  end
end

more detailed example at: blog.eq8.eu/article/order-attachments-in-rails-activestorage-has_many_attached.html

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

© 2024 GoRails, LLC. All rights reserved.