宝石蜻蜓。如何在编辑视图中创建当前文件列表?

时间:2016-03-08 20:31:36

标签: ruby-on-rails nested-attributes dragonfly-gem

我有模型项目,模型中有现场文件(文件)。我正在使用宝石蜻蜓。编辑项目时,如何制作当前文件列表?此时,在编辑页面上,文件列表字段显示:"未选择文件"。我接下来做了:

projects_controller:

def edit

    end

    def update
      if @project.update(project_params)
        redirect_to @project
      else
        render :edit
      end
    end

    private

    def set_project
      @project = Project.find(params[:id])
    end

    def set_payment_types
      @payment_types = PaymentOption.all
    end

    def project_params
      params.require(:project).permit(:title, :description, :price, :location, 
         :anonymity, :price_category, :category_id, :skill_list, documents_attributes: [:attachment], payment_option_ids: [])
    end

edit.html.erb

<%= form_for @project do |f| %>
  <p>
    <%= f.label 'Name' %>
    <%= f.text_field :title %>
  </p>
  <P>
    <%= f.label 'Budget' %>
    <%= f.text_field :price %>

    für

    <%= f.select :price_category, Project::PRICE_CATEGORIES %>
  </P>
  <p>
    <%= f.label 'Description' %>
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.label 'Category' %>
    <%= f.collection_select :category_id, Category.all, :id, :name %>
  </p>

  <p>
    <%= f.label 'Skills Freelancer (15 pieces) *' %>
    <%= f.text_field :skill_list %>
  </p>

  <p>
    <%= f.label 'Location' %>
    <%= f.text_field :location %>
  </p>


  <ul>
    <% @payment_types.each do |type| %>
      <li><%= check_box_tag 'project[payment_option_ids][]', type.id %>
        <%= type.name %>
      </li>
    <% end %>
  </ul>

  <p>
    <b>Anonymity order</b>
  </p>
  Setup allows for players to remain anonymous. Note that this may reduce the number of responses.

  <p>
    <%= f.label 'Place Order anonymously' %>
    <%= f.check_box :anonymity %>
  </p>

  <p>
    <%= f.fields_for :documents do |d| %>
      <%= render 'document_fields', f: d %>
    <% end %>
    <div class="links">
      <%= link_to_add_association 'add file', f, :documents %>
    </div>
  </p>


  <P>
    <%= f.submit 'Edit' %>
  </P>

<% end %>

_document_fields.html.erb:

<div class="nested-fields">

  <%= f.label :attachment %>
  <%= f.file_field :attachment %>

  <%= link_to_remove_association "remove file", f %>

</div>

document.rb

class Document < ApplicationRecord
    belongs_to :project

    dragonfly_accessor :attachment
end

在编辑页面上,文件列表字段显示:&#34;文件未被选中&#34;,但必须指定当前文件。

1 个答案:

答案 0 :(得分:0)

file_field仅用于上传新文件,而不用于显示数据库中已有的内容。要显示上传文件列表,您应该只显示文件名和/或带缩略图的图像标签,并提供销毁链接。 您还可以提供创建新附件的链接。

edit.html.erb

<div>
  <ul>
  <%= @project.documents.each do |document| %>
    <li>
      <%= document.attachment.name %>
      <%= link_to "Delete", document_path(document), method: :delete, data: { confirm: 'Are you sure you want to delete this?' } %>
    </li>
  <% end %>
  </ul>
  <div class="links">
    <%= link_to_add_association 'add file', f, :documents %>
</div>
</div>