javascript - 如何在 Rails Active Storage 中使用 Dropzone JS 进行多次上传?

标签 javascript ruby-on-rails ruby ruby-on-rails-5

我正在按照本教程使用 DropzoneJS 进行多个文件上传,但我不知道如何获取属于模型的多个图像以显示在“显示”页面中。尽管在 @post.feature_image 数组中执行了 .each,但当我上传多张图像时,仅显示一张图像。

教程在这里: https://web.archive.org/web/20191223022642/https://web-crunch.com/rails-drag-drop-active-storage-stimulus-dropzone/

示例仓库:https://github.com/justalever/drag_and_drop_active_storage

我为使其正常工作所做的更改: _form.html.erb

data-dropzone-max-files="10"

posts/show.html.erb

 <%= link_to @post do %>
    <% @post.feature_image.each do |image| %>
      <%= image_tag image %>
    <% end %>
  <% end %>

模型/post.rb

class Post < ApplicationRecord
  belongs_to :user
  has_many_attached :feature_image
end

请帮忙 - 我做错了什么?

最佳答案

在相同的教程和目标下遇到了相同的问题,我刚刚解决了!

  1. 您的关联名称采用复数形式,has_many_attached :feature_images
class Post < ApplicationRecord
  belongs_to :user
  has_many_attached :feature_images
end
  • multiple: true 添加到您的文件字段(不要忘记同时将关联名称复数化!)
  • <%= form.file_field :feature_images, direct_upload: true, multiple: true, data: { target: 'dropzone.input' } %>
    
  • 更新您的 post_params Controller 方法以允许一组 feature_images,而不是期望一个附件:
  • def post_params
      params.require(:post).permit(:title, :body, feature_images: [])
    end
    

    这应该就是全部了。更多信息请点击 https://guides.rubyonrails.org/active_storage_overview.html#has-many-attached

    关于javascript - 如何在 Rails Active Storage 中使用 Dropzone JS 进行多次上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60476387/

    相关文章:

    ruby - 用换行符替换管道字符 "|"?

    ruby-on-rails - 避免对 rails 中的表进行多次查询

    mysql - 无法使用 ruby​​ gem 访问 MySQL 数据库

    javascript - 重命名从 HTML5 Canvas 创建的图像

    javascript - 用Enzyme/Jest模拟点击测试不调用Sinon Spy

    ruby-on-rails - Rails - 函数 - 可重用代码块 - 如何? - 重构

    ruby-on-rails - Ruby 和 Rails "Date.today"格式

    javascript - 我想将查询返回的结果保存在变量中并在另一个函数中使用它

    javascript - TweenMax 没有动画 (GSAP)

    ruby-on-rails - 人类可读的 URL 会导致 Ruby on Rails 出现问题