ruby-on-rails 如何处理Rails附件在编辑我的资源时为nil?

iovurdzv  于 2023-10-21  发布在  Ruby
关注(0)|答案(1)|浏览(165)

我是ActiveStorage的新手。
我有一个名为Landing的模型,带有一个附件:image。(我使用的是ActiveStorage)。
当创建一个新的记录一切顺利,但当你更新任何属性,图像被删除,除非你再次上传附件。这是为什么呢?如果没有新的附件上传,我是否需要显式地告诉我的控制器处理附件逻辑?没有内置的助手吗?**

在我的表单中,我有以下输入:

  1. <%= f.file_field :image, class: "rounded input w-full my-2" %>

在我的控制器

  1. def update
  2. if @landing.update(landing_params)
  3. redirect_to admin_landings_path, notice: "Actualizado con éxito :)"
  4. else
  5. render :edit, status: :unprocessable_entity
  6. end
  7. end

我的模特

  1. has_one_attached :image do |attachable|
  2. attachable.variant(:thumb, resize_to_fill: [500, 500])
  3. attachable.variant(:big, resize_to_fill: [1200, 1200])
  4. end
23c0lvtd

23c0lvtd1#

通过ActiveStorage和has_many_attached关系,我们需要将其添加到生产和开发环境中:

  1. config.active_storage.replace_on_assign_to_many = false

这种方法对我很有效。

相关问题