Subscribe to my Feed, follow me on Twitter, recommend me on Working With Rails or see my code on GitHub
Paths
You can control which path the files will be written to by setting the save_path attribute on the model class:
class UploadedFile < ActiveRecord::Base
acts_as_file #Must come first
self.save_path = File.join(RAILS_ROOT, 'public', 'files')
self.read_path = 'files'
end
If you want to let people get access to the files through the browser (i.e. you save them in /public), remember to set the read_path as well. The url method provides a path that can be presented to the browser:
<%= link_to 'Download file', file.url %>
If you don’t set these attributes in your model class, they will default to public/uploads.
Instance-specific paths
The model instances also have attributes named save_path and read_path. These are by default a copy of the same attributes on the class itself, but can be overridden:
def create
upload = UploadedFile.new(params[:uploaded_file])
upload.save_path = File.join('some', 'other', 'path')
upload.save
end
I’m not sure how useful this is, and I recommend to use the path attribute instead if you want to customise each instance’s path:
class UploadedFile < ActiveRecord::Base
belongs_to :user
acts_as_file
self.save_path = File.join(RAILS_ROOT, 'public', 'files')
self.read_path = 'files'
#The file will now be saved in
#"public/files/#{user_id}/"
def path
user_id
end
end
