ruby-on-rails - Rails 7 - has_many_attached 加载新附件时删除旧附件

标签 ruby-on-rails ruby rails-activestorage ruby-on-rails-7

我在 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”,“个人资料”=>{“照片”=>#},“ Controller ”=>“个人资料”,“操作”=>“更新”,“id"=>"abcd"} 允许: false> [1m[36m配置文件加载(0.6ms)[0m [1m[34mSELECT 配置文件.* 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/

相关文章:

html - Rails 2 Mailer View 将 3D 添加到字符串

ruby-on-rails - Rails AJAX 请求返回 5 次而不是一次

ruby-on-rails - 从清除密码存储迁移到 authlogic

ruby - 如何使用 Ruby 找到最小值/最大值

ruby-on-rails - 获取 state_machine 状态列表

ruby-on-rails - rails 3.2 + OSX : Cannot install rmagick gem

html - 将 HAML 代码转换为普通 HTML 和代码

ruby-on-rails - "Request has expired"将 S3 与 Active Storage 一起使用时

ruby-on-rails - 渲染 json 中的 Rails Active Storage 图像链接

ruby-on-rails - rails : How to disable ActiveStorage Analyzers and Previewers