Rails 6 Active Storage:无法找到或构建 blob:预期可附加,得到 nil

Sim*_* Mo 6 ruby-on-rails rails-activestorage ruby-on-rails-6

刚刚创建了一个新的 Rails 6 应用程序,我试图通过使用 rails scaffold 生成的表单将图像添加到 active_storage blob 而不是替换它们。

遵循文档(https://guides.rubyonrails.org/active_storage_overview.html#has-many-attached),在我的控制器中使用 #attach ,但它会导致一个错误页面并保持替换所有的“默认”行为图像而不是添加新图像。

使用 Rails 6.0.0 和 active_storage 6.0.0

我首先创建了一个 Page 模型rails g scaffold Page name:string,然后在我的 page.rb 模型中添加了与 ActiveStorage 的关联has_many_attached :images

在我的表单中,我添加了一个 file_field,允许多次上传:

<%= form.file_field :images, multiple: true %>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器更新操作,请注意@page.images.attach(params[:images]),根据文档,它应该可以完成这项工作

<%= form.file_field :images, multiple: true %>
Run Code Online (Sandbox Code Playgroud)

在填写表格,附加新图片并发布时,我收到以下错误:

ArgumentError in PagesController#update
Could not find or build blob: expected attachable, got nil 
Run Code Online (Sandbox Code Playgroud)

指向线 @page.images.attach(params[:images])

检查服务器日志时,我注意到尽管出现错误,但默认行为仍在运行:旧图像被删除,新图像被附加。

小智 15

在 Rails 6 下,has_many_attached 的默认行为从 Rails 5 更改。以前,文件被附加到附件列表而不是被覆盖。

幸运的是,可以在 application.rb 中更改此默认值:

config.active_storage.replace_on_assign_to_many = false
Run Code Online (Sandbox Code Playgroud)

然后,您可以将该images: []部分保留在允许列表中并@page.images.attach(params[:images])完全删除该呼叫。

  • config.active_storage.replace_on_assign_to_many 已弃用,并将在 Rails 7.1 中删除。https://github.com/rails/rails/blob/c8c447240c95921d98a79cf6380e5d843bba0331/activestorage/lib/active_storage/attached/model.rb#L150 (2认同)

Sim*_* Mo 4

好的,我可以解决这个问题!

问题:update动作将取代所有图片。

这就是我所做的:

images: []1)我从允许列表中删除(强参数)

2)我编写了这段代码来单独附加每个新图像并将其放入createactions中update

    if params[:page][:images].present?
      params[:page][:images].each do |image|
        @page.images.attach(image)
      end
    end
Run Code Online (Sandbox Code Playgroud)

#attach实际上会允许该参数。

不确定这是最好的方法,但现在它有效