I am trying to display the filename of a Carrierwave attachment in a Rails erb template. The following does not work:
<%= @page.form.filename %>
You're right @epylinkn. Documentation points towards using:
@page.form.file.identifier
But when I use that, I always get nil
(just as @Cheng commented).
I then inspected my objects methods (@page.form.file.methods.inspect
), and found the following to work:
@page.form.file_identifier
The documentation you're looking at is the sanitized file, it's what it uses for actually storing a file. The part you're looking for is FormUploader, which is an Uploader, and part of http://rubydoc.info/gems/carrierwave/0.5.2/CarrierWave/Uploader
If you want to get the file name, you could either read it from the database column directly, or use File.basename(@page.form.path)
to extract it easily.
CarrierWave::SanitizedFile
has a private original_filename
method containing the filename of the uploaded file. (docs: http://rdoc.info/github/jnicklas/carrierwave/master/CarrierWave/SanitizedFile:original_filename)
After reading through this thread from the CarrierWave mailing list, none seemed to fit my needs. With something like
class Upload < ActiveRecord::Base
mount_uploader :file, FileUploader
# ...
I heavily modify the :file
column value from the original filename. Due to this I decided to track the original filename in a separate column from the one bound to CarrierWave. In my FileUploader
I simply added a reader that wraps the private original_filename
method:
def original_file
original_filename
end
I then added a before_create
event to the Upload
class (my Upload
records are never modified, so a before_create
is acceptable for my needs)
before_create do
self.original_file = self.file.original_file
end
This is my solution:
before_save :update_file_attributes
def update_file_attributes
if file.present? && file_changed?
self.content_type = file.file.content_type
self.file_size = file.file.size
self.file_name = read_attribute(:file)
end
end
If you're using ActiveRecord, you can directly access the field named form
in two ways:
def my_method
self[:form]
end
or
def my_method
form_before_type_cast
end
The second method is read-only.
In your model's associated uploader class, define a filename method.
def filename
File.basename(path)
end
You can then call
model_instance.file.filename
Works as of CarrierWave 1.1.0. This is a succinct restatement/amalgamation of kikito and Chris Alley's responses above.