ruby-on-rails - 如何在 ActiveStorage Rails 5.2 实现中检索源文件名?

标签 ruby-on-rails rails-activestorage

尽管我发现了同样的问题here ,我可以上传文件,但无法检索原始文件名。

从 BusinessObject 中,我创建一个加载文件的范围:

app/views/scopes/_form.html.erb
<%= form_with model: [@business_object, @scope], html: {id: "edit_form"} do |f| %>
  <!-- apply template to Scope -->
  <%= render partial: "shared/object_definition_form", locals: {this_object: @scope, f: f} %>

  <!-- additional fields -->
  <div class="row">
    <div class="col-md-2 text-right"><%= t('FileUpload') %>:
    </div>
    <div class="col-md-10 field"><%= f.file_field :uploaded_file, class: "btn btn-primary" %>
    </div>
  </div>
  <%= f.submit "Validate" %>
<% end %>

范围 Controller 按预期附加文件,但它还应该将文件名存储在resource_file字段中:

app/controllers/scopes_controller.rb
def update
    ### Scope retrieved by Callback function
    @scope.updated_by = current_login
    if params.has_key?(:uploaded_file)
      @scope.uploaded_file.purge
      @scope.uploaded_file.attach(params[:uploaded_file])
      @scope.resource_file = self.uploaded_file.blob.filename
    end

    respond_to do |format|
      if @scope.update_attributes(scope_params)
        format.html { redirect_to @scope, notice: 'Scope was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @scope.errors, status: :unprocessable_entity }
      end
    end
  end

我尝试了多种方法来获取原始文件名,但无法做到。 任何想法 ? 谢谢!

最佳答案

附加文件后,您可以通过以下方式检索原始文件名:

@scope.uploaded_file.filename

关于ruby-on-rails - 如何在 ActiveStorage Rails 5.2 实现中检索源文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59389525/

相关文章:

Javascript 仅在刷新后加载(Ruby on rails - Materialize CSS)

ruby-on-rails - MathJax、Rails 4、Markdown 集成

ruby-on-rails - RubyMine 对 SASS 的支持

ruby-on-rails - 如何避免在 find 方法中出现 `hardcoding` id?

javascript - 使用 Javascript 上传到 Rails Active Storage

ruby-on-rails - 如何在Rails 5.2中复制存储在ActiveStorage中的文件

ruby-on-rails - Rails ActiveRecord 创建或查找

ruby-on-rails - 如何将 has_one_attached 转换为 has_many_attached 到带有 has_one 附件的现有表?

html - Rails - 使用 Active Storage 在新选项卡中打开图像

ruby-on-rails - Rails 中未显示视频 HTML 标记