user1185081
user1185081

Reputation: 2118

How to retrieve the source filename in ActiveStorage Rails 5.2 implementation?

Eventhough I found the same question here , I can upload a file, but I cannot retrieve the original filename.

From a BusinessObject, I create a Scope which loads a file:

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

The scopes controller attaches the file as expected, but it should also store the filename in the resource_file field:

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

I tried several ways to get the original filename, but could not do it. Any idea ? Thanks!

Upvotes: 3

Views: 2572

Answers (1)

bunufi
bunufi

Reputation: 764

After you have attached the file, you can retrieve the original filename by:

@scope.uploaded_file.filename

Upvotes: 4

Related Questions