刚刚创建了一个新的 Rails 6 应用程序,我试图通过使用 Rails 脚手架生成的表单将图像添加到 active_storage blob,而不是替换它们。
遵循文档(https://guides.rubyonrails.org/active_storage_overview.html#has-many-attached https://guides.rubyonrails.org/active_storage_overview.html#has-many-attached),在我的控制器中使用 #attach,但它会导致错误页面并保留替换所有图像而不是添加新图像的“默认”行为。
将 Rails 6.0.0 与 active_storage 6.0.0 结合使用
我首先使用制作了一个页面模型rails g scaffold Page name:string
然后在我的 page.rb 模型中添加与 ActiveStorage 的关联has_many_attached :images
在我的表单中,我添加了一个 file_field,允许多次上传:
<%= form.file_field :images, multiple: true %>
这是我的控制器更新操作,请注意@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])
在检查服务器日志时,我注意到尽管出现错误,但默认行为仍在运行:旧图像被删除,新图像被附加。