gpt4 book ai didi

ruby-on-rails - Rails 6 Active Storage : Could not find or build blob: expected attachable, 为零

转载 作者:行者123 更新时间:2023-12-01 23:14:40 25 4
gpt4 key购买 nike

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

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

使用 Rails 6.0.0 和 active_storage 6.0.0

我首先使用 rails g scaffold Page name:string 制作了一个 Page 模型然后在我的 page.rb 模型中添加了与 ActiveStorage 的关联 has_many_attached :images
在我的表单中,我添加了一个 file_field,允许多次上传:

<%= form.file_field :images, multiple: true %>

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


def update

respond_to do |format|
if @page.update(page_params)

@page.images.attach(params[:images])

format.html { redirect_to site_pages_path(@site), notice: 'Page was successfully updated.' }
format.json { render :show, status: :ok, location: @page }
else
format.html { render :edit }
format.json { render json: @page.errors, status: :unprocessable_entity }
end
end
end


在填写表格,附加新图片并发布时,我收到以下错误:
ArgumentError in PagesController#update
Could not find or build blob: expected attachable, got nil

指向线 @page.images.attach(params[:images])
检查服务器日志时,我注意到尽管出现错误,但默认行为仍在运行:旧图像被删除,新图像被附加。

最佳答案

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

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

config.active_storage.replace_on_assign_to_many = false

然后您可以保留 images: []允许列表中的部分并删除 @page.images.attach(params[:images])完全调用。

关于ruby-on-rails - Rails 6 Active Storage : Could not find or build blob: expected attachable, 为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58282845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com