我在 Rails 7 下使用 Active Storage 时遇到问题。
我读了一些帖子,但都是关于 Rails 5-6 的,并且从那时起有些方法就被弃用了。
问题 - 当我尝试上传第二张照片时,旧照片被删除。为什么?如何解决这个问题?
我有型号:
class Profile
has_many_attached :photos
has_one_attached :avatar
在 Controller 中:
class ProfilesController < ApplicationController
def update
Rails.logger.debug params.inspect
@profile = current_user.profile
@profile.update(profiles_params)
private
# Only allow a list of trusted parameters through.
def profiles_params
params.require(:profile).permit(:id, :email, :marketing,
:marketing_second, :terms,
:personal_data,
:birthdate, :avatar, :photos )
end
View 中:
<%= form_for @profile do |f| %>
<div class='upload_container'>
<%= f.file_field :photos, accept:'image/*',
:class=>'file_field_custom', required: true %>
<%= f.button "Upload", type:'submit', :class=>'photos_submit_button' %>
</div>
<% end %>
这已从 Rails 7 中删除:
config.active_storage.replace_on_assign_to_many = false
日志:
#<ActionController::Parameters {"_method"=>"patch",
“authenticity_token”=>“y5n4UgRhRWFB9Q0L3J1roxK3dhuijRQk7Fng6sjHU52G0KDs9OJlYt8nmshG8HYnlrk7JB9x3QHDO8_GQnDwsA”,“个人资料”=>{“照片”=>#配置文件
.* FROM 配置文件
WHERE 配置文件
.user_id
= 1 LIMIT 1[0m
↳ app/models/user.rb:59:在“个人资料”中
[1m[36mActiveStorage::Attachment Destroy (4.4ms)[0m [1m[31mDELETE FROM
`active_storage_attachments` WHERE `active_storage_attachments`.`id` = 334[0m
↳ app/controllers/profiles_controller.rb:133:in `update'
为什么会触发 Destroy 操作。
最佳答案
@profile.photos.attach(params[:profile][:photos])
在 Controller 的更新操作中
关于ruby-on-rails - Rails 7 - has_many_attached 加载新附件时删除旧附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75176859/