Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the file name that we upload using carrierwave in rails

i am using carrierwave for uploading and downloading the files. This is my model:

class InvoiceDetail < ActiveRecord::Base
    mount_uploader :attachment, AttachmentUploader
  validates :invoice_number, :supplier_name, :attachment, presence: true    
  validates_uniqueness_of :invoice_number
end

attachment/uploader.rb:

 def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

invoice_detail/_form.html.erb:

<%= form_for(@invoice_detail , html: {class: 'form-horizontal', role: 'form' }) do |f| %>

    <div class="field">
        <%= f.label :invoice_number, :class => 'control-label' %>
            <div class="controls">
    <%= f.text_field :invoice_number, :class => 'text_field' %>
  </div>
  </div>
    <div class="field">
    <%= f.label :supplier_name, :class => 'control-label' %>
                <div class="controls">

    <%= f.text_field :supplier_name, :class => 'text_field' %>
    </div>
  </div>

     <div class="control-group">
      <%= f.label :attachment , :class => 'control-label' %>
      <div class="controls">
        <%= f.file_field :attachment, :class => 'file_field' %>
      </div>
    </div>
  <div class="form-actions">
    <%= f.submit "Create Invoice Details", :class => 'btn btn-primary' %>
    <%= f.submit "cancel", :class => 'btn btn-danger', method: :delete, data: { confirm: 'Are you sure you want to cancel' } %>

  </div>
<% end %>

The file which I upload is stored in public/uploads folder of my rails application. Now my requirement is to upload the file with invoice_number i am entering in the form and when I click on download, the file has to be downloaded with same Invoice number. (For example, i am entering my invoice number as :1234 and uploading file with name example.xlsx, the uploaded file has to be stored as 1234.xlsx) Please help me out.

like image 814
venkat Avatar asked Feb 27 '15 05:02

venkat


1 Answers

You can rename file during upload:

def filename
  "#{model.invoice_number}.#{file.extension}" if original_filename.present?
end
like image 101
Maxim Avatar answered Sep 20 '22 10:09

Maxim