Save 36% for Black Friday! Learn more

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Get Paperclip file before save

Agung Setiawan asked in Rails

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.

Reply

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
Reply

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 😅

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,110+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.