更改我们在 rails 中使用载波上传的文件名

Changing the file name that we upload using carrierwave in rails

我正在使用 carrierwave 上传和下载文件。 这是我的模型:

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 %>

我上传的文件存储在我的 rails 应用程序的 public/uploads 文件夹中。 现在我的要求是上传我在表格中输入的 invoice_number 的文件,当我点击下载时,必须使用相同的发票编号下载文件。 (例如,我输入的发票编号为:1234 并上传名称为 example.xlsx 的文件,上传的文件必须存储为 1234.xlsx) 请帮帮我。

你可以rename file during upload:

def filename
  "#{model.invoice_number}.#{file.extension}" if original_filename.present?
end