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.
You can rename file during upload:
def filename
"#{model.invoice_number}.#{file.extension}" if original_filename.present?
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With