【问题标题】:rails file_field not showingrails file_field 未显示
【发布时间】:2021-01-13 12:11:41
【问题描述】:

我想让我的应用通过 Shrine 上传多个文件,但 one doc 建议使用两个 file_fields,而 other 建议只使用一个。在他们的讨论论坛发布问题后,有人建议我隐藏名为files[] 的问题。无论我是否这样做,第一个 file_field 总是无法渲染。为什么这个字段不显示?

<%= form_for @item, html: { enctype: "multipart/form-data" } do |f| %>
 <%= f.fields_for :photos do |i| %>
  <%= i.label :image %>
  <%= i.hidden_field :image, value: i.object.cached_photos_data, class: "upload-data" %>
  <%= i.file_field :image, class: "upload-file" %> /// why is this not rendering?????
 <% end %>
 <%= file_field_tag "files[]", multiple: true %> // what purpose does this one serve?
 
 <%= f.text_field :title %>
      
 <%= f.submit "Submit" %>    
<% end %>

型号:

class Item < ApplicationRecord
 has_many :photos, as: :imageable, dependent: :destroy
end

class Photo < ApplicationRecord
 include ImagesUploader::Attachment(:image)
 belongs_to :imageable, polymorphic: true
 validates_presence_of :image
end

控制器:

class ItemsController < ApplicationController
 def new
  @item = current_user.items.new
 end

 def create
  @item = current_user.items.create(item_params)
  @item.save
 end

 private
 def item_params
  params.require(:item).permit(:title, photos_attributes: { image: [] })
 end
end

【问题讨论】:

  • 2020 年推荐使用 active_storage 在 Ruby on Rails 中上传文件edgeguides.rubyonrails.org/active_storage_overview.html#
  • @Yshmarov Active Storage 一旦你开始使用它就很糟糕。它即时生成版本(为什么有人想在生产中执行此操作超出了我的范围),它减少了对 S3 中存储的控制,并且执行了不必要的数据库查询。这样不好。各地的专业推荐都是去神社。

标签: ruby-on-rails shrine uppy


【解决方案1】:

仔细阅读第一个链接:它说单个字段(i.file_field :image)用于显示现有图像(这就是为什么它在示例中被包裹在f.fields_for :photos中)和多个字段(file_field_tag "files[]", multiple: true)是用于上传新文件。因此,如果您的 @item 没有 :image,则不会显示该字段。

如果需要进一步澄清,请告诉我 - 很乐意提供帮助!

【讨论】:

  • 您也可以build 在您的控制器中多次使用该关系。因此,在新操作中,您可以执行3.times { @item.photos.build },这将启动关系并允许字段显示在表单中
猜你喜欢
  • 2021-10-11
  • 2014-04-30
  • 1970-01-01
  • 2011-06-22
  • 2012-08-01
  • 2017-10-31
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多