我使用carrierwave上传和下载文件。 这是我的模特:
class InvoiceDetail < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
validates :invoice_number, :supplier_name, :attachment, presence: true
validates_uniqueness_of :invoice_number
end
附接/ 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) 请帮帮我。
答案 0 :(得分:6)
def filename
"#{model.invoice_number}.#{file.extension}" if original_filename.present?
end