marcamillion
marcamillion

Reputation: 33775

How do I change the name of the file field in simple_form when a file exists?

I have a Profile model that:

  has_many :transcripts, dependent: :destroy
  accepts_nested_attributes_for :transcripts, allow_destroy: true

So on my app/views/profiles/_form.html.erb, I have the following:

      <%= f.simple_fields_for :transcripts do |transcript| %>
        <%= render 'transcript_fields', f: transcript %>
      <% end %>

And the app/views/profiles/_transcript_fields.html.erb looks like this:

<%= f.file_field :attachment, class: 'col-lg-4 form-control' %>

So what I want to do is on the _transcript_fields partial, when the profile has existing transcripts, I want it to display a file field that has the name of the file attached -- that way if they want to change that file that was attached, they can just click upload on that same file_field and it will update that Transcript record.

I have the actual update operation working now, but what happens is, it just shows the fields like this:

enter image description here

Where the top file_field is the existing file, and the bottom one reflects a new field that can be added.

Upvotes: 3

Views: 2222

Answers (2)

Ankit Pandey
Ankit Pandey

Reputation: 460

You can't.

The only way to set the value of a file input is when the user selects a file from his system.If you will do it forcefully it will apper like this in HTML.

<form name="foo" method="post" enctype="multipart/form-data">
  <input type="file" value="c:/rails.png">
</form>

This is done for security reasons. Otherwise you would be able to create a Javascript that automatically uploads a specific file from the clients computer, but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:

  1. Show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail.
  2. The file_field to upload a new file.
  3. A checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value.

Hope I answered your question.

Upvotes: 7

zwippie
zwippie

Reputation: 15515

In the _transcript_fields partial you can check if the current transcript object is already persisted or not. Based on that, it's possible to render something different.

Something like:

# app/views/profiles/_transcript_fields.html.erb
<% if f.object.persisted? %>
  <%= f.object.name %>
<% else %>
  <%= f.file_field :attachment, class: 'col-lg-4 form-control' %>
<% end %>

Upvotes: 2

Related Questions