Question

For the record, I'm working on legacy code and I'm trying to plug a new feature without breaking everything. Right now I have a bunch of files on my server as such:

 myapp/public/temp/myfile.doc

The thing is that I want to create a Docfile object from these files in a controller action.

Here is the trimmed down Docfile class:

class DocFile < ActiveRecord::Base
  has_attached_file :docs,
    :path => "#{Constants::DOCFILES_PATH}:basename.:extension",
    :url => "http://#{Constants::SITE_URL}/docs/:basename.:extension"
end

Paperclip has some nice documentation if you upload from a form, but not in my situation.

So how can I "simulate" the fact that I'm uploading a file?

So far I've tried this:

temp_file_url = "correct_rails_root/myapp/public/temp/myfile.doc"
@docfile = DocFile.new :docs => temp_file

But it's not working.

Any pointers would be appreciated!

Edit:

I did this:

temp_file_url = Constants::TEMPORARY_UPLOAD_PATH + "/" + params[:temp_file_upload][:doc]
temp_file = File.new(temp_file_url,  "w+")
@docfile = DocFile.new :docs => File.open(temp_file_url)

It's still not working

Was it helpful?

Solution

I had to do this:

temp_file_name = #the filename
temp_file_path = Constants::TEMPORARY_UPLOAD_PATH + "/" + temp_file_name
temp_file = File.new(temp_file_path,  "r")

@docfile = DocFile.new :docs => temp_file

Apparently if I did not open the file as "read" it would not work. It makes very little sense to me but it works now!

OTHER TIPS

I am not an authority on Rails but,

@docfile = DocFile.new :docs => temp_file

shouldn't it be

@docfile = DocFile.new :docs => temp_file_url  

You should pass Paperclip a File object:

temp_file_path = 'correct_rails_root/myapp/public/temp/myfile.doc'
@docfile = DocFile.new :docs => File.open(temp_file_path)

I think you will need to address this with a migration and for your existing files you will need to populate the columns that paperclip adds to your model (xxx_file_name, xxx_content_type, xxx_file_size). You didn't mention if Constants::DOCFILES_PATH is mapped to your legacy document directory, but even so I think you will have to symlink to these files to the directory structure that paperclip expects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top