All threads / Get Paperclip file before save

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.

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 😅

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.