Paperclip - Running a method after the file is saved?

雨燕双飞 提交于 2019-12-06 21:38:28

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/19960471/paperclip-running-a-method-after-the-file-is-saved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!