Fernando
Fernando

Reputation: 127

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?

Upvotes: 4

Views: 3019

Answers (3)

s3tjan
s3tjan

Reputation: 1168

Rails has not added the ability to add validations to file attachments. See Issue #31656

Try this approach:

Validate for mime-types:

<%= f.file_field :photos, accept: "image/png,image/gif,image/jpeg', multiple: true %>

You still need to add model validations. See this post Validating the Content-Type of Active Storage Attachments on how to use a custom validator.

To limit your action to be executed only once, you could add a boolean field to your model and set it to true after your action terminates successfully. Use a before_update as Antarr Byrd suggested to check after each photo is attached to your model.

Upvotes: 0

Antarr Byrd
Antarr Byrd

Reputation: 26061

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

Upvotes: 5

Igor Kasyanchuk
Igor Kasyanchuk

Reputation: 774

Check callbacks (after_create, after_save, etc) in rails models and options "on: :create" and "update".

Upvotes: 0

Related Questions