istan
istan

Reputation: 1359

pass file to paperclip on back end [rails]

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!

Upvotes: 2

Views: 2279

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

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!

Upvotes: 9

Related Questions