Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 845
Jonmichael Chambers Avatar asked Nov 13 '13 17:11

Jonmichael Chambers


2 Answers

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

like image 30
Clayton Selby Avatar answered Sep 30 '22 06:09

Clayton Selby


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.

like image 144
Grocery Avatar answered Sep 30 '22 08:09

Grocery