简体   繁体   中英

Let user order images in an has_many_attached relation with ActiveStorage

Is there a way to let user chose the order of images?

Let say we have a Product model with has_many_attached:images And we want to let user chose the order of images (like with a drag and drop tool), for instance the first one will be profile image.

Do you recommand a model implementation for that usecase?

Yes.

ActiveStorage takes an approach to file uploads where you store all the data about attachments in a single repository instead of having separate tables per model or adding columns to the model. This is the tradeoff made to make it just magically work when you add has_many_attached:images to the model.

ActiveStorage is just an abstraction around storing the file somewhere so that you can later retrieve it. Don't confuse it with the "thing" which is the entity in your business logic.

If you're adding a bunch of business logic (custom ordering, captions, etc) to the uploads you should really create your own model that represent the entity in your specific domain and not monkeypatch your business logic into ActiveStorage.

For example a ProductPhoto as a higher level concept isn't actually the same thing as just the JPG file. Its a link to the file, captions etc.

class Product < ApplicationRecord
  belongs_to :primary_image, class_name: 'ProductPhoto', 
                             optional: true
  has_many :product_photos
  accepts_nested_attributes_for :product_photos
end

# rails g model ProductPhoto product:belongs_to sequence:integer 
class ProductPhoto < ApplicationRecord
  belongs_to :product
  has_one_attached :image
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM