Displaying a Carrierwave filename in the view

前端 未结 10 1124
暖寄归人
暖寄归人 2020-12-13 23:29

I am trying to display the filename of a Carrierwave attachment in a Rails erb template. The following does not work:

<%= @page.form.filename %>
         


        
10条回答
  •  不思量自难忘°
    2020-12-13 23:53

    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
    

提交回复
热议问题