【问题标题】:How to use Simple Form and Direct Upload ActiveStorage如何使用简单表单和直接上传 ActiveStorage
【发布时间】:2019-11-13 14:02:13
【问题描述】:

我在尝试使用 Simple Form gem 上传视频时遇到了问题。我为此使用 ActiveStorage 和本地存储。 我的表单如下所示:

= simple_form_for @film do |f|
  = f.error_notification
  = f.input :title, as: :string
  = f.input :description, as: :string
  = f.input :cover_img, as: :file

  = f.input :film_link, as: :file, direct_upload: true
  = f.button :submit
  = link_to 'back', :back, class: 'btn btn-secondary'

我已按照此处的说明进行操作 https://edgeguides.rubyonrails.org/active_storage_overview.html 所以我在我的应用程序中包含了 js 和 css 文件。但这行不通。通过 simple_form 传递 direct_upload: true 似乎有些麻烦。 我还找到了文章 https://phase2online.com/blog/2018/10/03/easily-upload-files-with-active-storage-in-rails-5-2/ 并从 here 拉 git repo

当您在 _form 上使用 form_for 时,这将起作用。当我将表单更改为使用 simple_form gem(而不是 form_form 使用 simple_form_for)时,它将不起作用。

有人知道为什么这不起作用吗? 我使用 ruby​​ 2.6.3 和 Rails 5.2.3 和 simple_form (5.0.1)

【问题讨论】:

  • 代替f.input,尝试使用f.file
  • 使用 f.file_field 而不是 f.input 将使此直接上传工作,但不会显示来自简单表单的所有错误消息。还是谢谢

标签: ruby ruby-on-rails-5 simple-form rails-activestorage


【解决方案1】:

有办法让这项工作发挥作用。

  1. 我们可以按照hashrocket 的建议将 f.input 更改为 f.file_field - 但是简单表单的验证将不起作用,也许我们必须在此输入和额外的 div 之前添加类。
  2. 我们可以在 f.input 中添加 html 属性。

对我来说这是有效的,我希望它也能帮助其他人。

= simple_form_for @film do |f|
  = f.error_notification
  = f.input :title, as: :string
  = f.input :description, as: :string
  = f.input :cover_img, as: :file, input_html: { data: { direct_upload_url: '/rails/active_storage/direct_uploads' } }
  = f.input :film_link, as: :file, input_html: { data: { direct_upload_url: '/rails/active_storage/direct_uploads' } }
  = f.button :submit
  = link_to 'back', :back, class: 'btn btn-secondary'

【讨论】:

  • 次要建议:不要硬编码直接上传 url (direct_upload_url: '/rails/active_storage/direct_uploads'),而是使用 url helper 的路径:direct_upload_url: rails_direct_uploads_url(我在这里使用绝对 URL,因为默认表单处理程序在使用时也会这样做direct_upload: true)
【解决方案2】:

我建议简单地为此添加一个自定义输入,以避免在您的视图文件中重复。把这个放到文件app/inputs/direct_upload_file_input.rb:

# frozen_string_literal: true
class DirectUploadFileInput < SimpleForm::Inputs::FileInput
  def input_html_options
    super.merge({ direct_upload: true })
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-15
    • 2018-07-01
    • 2019-02-02
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多