Skip to main content

Get Paperclip file before save

Rails • Asked by Agung Setiawan

Is it possible to read the file, in my case image file, inside Paperclip::Attachment before the file is saved?

I need to send the image to an api first and then from the response it's given if it is accepted the model and the image will be saved. Otherwise do nothing.


That's a fun one. I would imagine you could build a validation for this that would do what you want.

Some pseudo code for you:

class Model
  has_attached_file :attachment

  validates :attachment_against_api

    def attachment_against_api
      response = API.send(attachment)
        errors.add(:attachment, response.message) if response.failure
    end
end

Turns out it is as easy as this

Paperclip.io_adapters.for(model.attachment).read

I tried this piece of code yesterday but didn't work and only gave me nil. The cause is I write that code before model.attachment is assgined 😅


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.