pass file to paperclip on back end [rails]

三世轮回 提交于 2019-12-22 12:32:31

问题


I am using paperclip to attach multiple files to a Entry object

Class Asset < ActiveRecord::Base

    belongs_to :entry

    has_attached_file :asset, ...

Works wonderfully when user is uploading files via a nested form. However, I have certain instances in which a file is uploaded not via the input form but as a result of a flash audio recorder. Audio is recorded and uploaded asynchronously to my /tmp folder. So I end up with some files on my server that have not been uploaded via paperclip.

In these cases, I'd like to take the file and pass it to paperclip to be handled as if it were uploaded by a user via the input form. i.e. I need to utilize paperclip programmatically from within a controller.

How would you go about accomplishing this? Many thanks!


回答1:


Ordinarily an uploaded file is passed to your controller as a File object in the params hash, which is then handed by the constructor, by way of attributes=, to the setter method created by Paperclip's has_attached_file--in your model's case Asset#asset= (might want to clarify those names a bit).

No, that's not an answer to your question, but it leads us to the answer. Knowing that you might realize that you can call that setter any time you want with a File as the parameter. E.g.:

class SomeController < ActionController::Base
  def some_action
    @some_asset = Asset.find 123 # (for example)

    file_path = '/tmp/path/to/your/file'
    file      = File.open(file_path, 'r')

    @some_asset.asset = file
    @some_asset.save
  end
end

Hope that's helpful!



来源:https://stackoverflow.com/questions/7669705/pass-file-to-paperclip-on-back-end-rails

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