Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
Fernando Avatar asked Sep 15 '25 20:09

Fernando


1 Answers

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? }

like image 137
Antarr Byrd Avatar answered Sep 18 '25 18:09

Antarr Byrd