Jonmichael Chambers
Jonmichael Chambers

Reputation: 125

Paperclip - Running a method after the file is saved?

I'm working on a project that needs to accept file uploads. After the file is uploaded, I'm doing some processing - extracting information from the file. I eventually plan to run this in a background worker, but it's currently running inline.

I've tried making use of both after_create and after_save to process the file, but it seems my method is ran before the save method from Paperclip - so my tests fail with "No such file or directory".

Is there any way to trigger the save method early, or to somehow run my method after the file has been saved to the file system?

Upvotes: 10

Views: 5267

Answers (4)

Matouš Borák
Matouš Borák

Reputation: 15954

I think the problem might be related to the order of callbacks.

As discussed in other answers, the attachment file is indeed physically saved to disk in an after_save callback defined in Paperclip which is added to the model class at the point of has_attached_file call.

So you must ensure that your own after_save callbacks (that want to deal with the uploaded file) are defined after the has_attached_line.

Note: the after_create callback indeed cannot be used at all as it is called before after_save.

Upvotes: 3

Clayton Selby
Clayton Selby

Reputation: 1254

Adding this answer for visibility. A previous comment by @Jonmichael Chambers in this thread solved the problem for me.

Change the callback from after_save/after_create to after_commit

Upvotes: 3

Grocery
Grocery

Reputation: 2274

You can't read paperclip file in a callback as it's not saved to filesystem yet (or butt). Why, I'm not exactly sure.

EDIT: Reason is that paperclip writes out the file via after_save callback. That callback happens after after_create

However you can get the file payload for your processing. For example:

class Foo < ActiveRecord::Base

  has_attached_file :csv

  after_create :process_csv

  def process_csv
    CSV.parse(self.csv.queued_for_write[:original].read)
    # .. do stuff
  end

end

I had to do this 2 minutes ago. Hope this helps.

Upvotes: 7

kafuchau
kafuchau

Reputation: 5593

Take a look at the Paperclip post processing events callbacks. You should be able to call after_post_process to do your extra file info extraction.

Upvotes: 0

Related Questions