views:

160

answers:

4

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

+1  A: 

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
Anand
this is true, dunnow if it's going to impact ^^ I'm testing right now
marcgg
I tried, didn't change a thing.
marcgg
A: 

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.

Jeff Paquette
Thanks for the answer. All this is done. Paperclip is working properly when used with a "normal" form. This situation is different so this is just some hacking around... any idea?
marcgg
+1  A: 

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)
mtyaka
It makes sense. I tried and it's not working. See my edit
marcgg
+1  A: 

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!

marcgg