看起来有一个配置 https://guides.rubyonrails.org/configuring.html#config-active-storage-replace-on-assign-to-many正是这样做的
config.active_storage.replace_on_assign_to_many = false
不幸的是,根据当前的 Rails 源代码,它已被弃用,并且它将被弃用Rails 7.1 中删除了 https://github.com/rails/rails/blob/v7.0.2.3/activestorage/lib/active_storage/attached/model.rb#L150
config.active_storage.replace_on_assign_to_many
已弃用并将在 Rails 7.1 中删除。确保您的代码可以很好地工作config.active_storage.replace_on_assign_to_many
set to true
升级之前。
要将新的可附加项附加到 Active Storage 关联,请优先使用attach
。
使用关联设置器将导致清除现有附加附件并用新附件替换它们。
看起来像明确使用attach
将是唯一的前进道路。
所以一种方法是在控制器中设置所有内容:
def update
...
if model.update(model_params)
model.files.attach(params[:model][:files]) if params.dig(:model, :files).present?
else
...
end
end
如果您不喜欢在控制器中包含此代码。例如,您可以覆盖模型的默认设置器,如下所示:
class Model < ApplicationModel
has_many_attached :files
def files=(attachables)
files.attach(attachables)
end
end
不确定我是否会建议这个解决方案。我更愿意添加新方法来附加文件:
class Model < ApplicationModel
has_many_attached :files
def append_files=(attachables)
files.attach(attachables)
end
end
并在你的表格中使用
<%= f.file_field :append_files %>
它可能还需要模型中的阅读器,可能还需要一个更好的名称,但它应该演示这个概念。