Search code examples
ruby-on-railsrails-activestorage

Do action after upload file with Active Storage


My model has a has_many_attached :photos.

The first time this model is created, it has 0 photos. If I run photos.attached? I get false.

When the user uploads some files to photos, I need to do some actions, but only the first time. I tried using before_update :if photos.attached?. But I need to know if the user is updating photos specifically.

Is there a way to know if the user is trying to update photos? Or is there a simple way to do this?


Solution

  • There is the dirty? method that you can use

    class Post < ApplicationRecord
      has_many_attached :photos
    
      before_update :do_whatever, if: -> { photos.dirty? } 
    
      def do_whatever
        # doing something
      end
    end
    

    You might also be able to try before_update :do_whatever, if: -> { photos_changed? }