You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails5.1升级6.1后Paperclip的add_attachment迁移报错如何修复

修复方案

核心报错原因

  • 你使用的paperclip ~> 5.0.0版本不兼容Rails 6.1,Paperclip从6.0.0版本才开始支持Rails 6系列,低版本的add_attachment、t.attachment等迁移辅助方法无法在Rails 6.1环境中被正确加载
  • 旧迁移中使用类方法self.up/self.down的写法,也不符合Rails 6.1迁移的默认规范

修复步骤

方案一:升级Paperclip到兼容版本(适合计划继续使用Paperclip的场景)

  1. 修改Gemfile中paperclip的版本声明:
gem 'paperclip', '~> 6.1.0'
  1. 执行命令更新依赖:
    bundle update paperclip
  2. 修正迁移文件写法:
class AddAttachmentAvatarToUsers < ActiveRecord::Migration[6.1]
  def up
    add_attachment :users, :avatar
  end

  def down
    remove_attachment :users, :avatar
  end
end

方案二:使用原生迁移写法(无第三方依赖,更稳妥)

因为Paperclip已经官方停止维护,后续如果要迁移到Active Storage等其他上传组件,原生写法不会残留历史包袱,直接替换迁移文件内容即可:

class AddAttachmentAvatarToUsers < ActiveRecord::Migration[6.1]
  def up
    add_column :users, :avatar_file_name, :string
    add_column :users, :avatar_content_type, :string
    add_column :users, :avatar_file_size, :bigint
    add_column :users, :avatar_updated_at, :datetime
  end

  def down
    remove_column :users, :avatar_file_name
    remove_column :users, :avatar_content_type
    remove_column :users, :avatar_file_size
    remove_column :users, :avatar_updated_at
  end
end

额外兼容配置

修改完成后如果仍有加载异常,在config/application.rb中添加如下配置:

# 兼容Rails 6.1序列化白名单规则
config.active_record.yaml_column_permitted_classes = [Symbol, Date, Time, ActiveSupport::TimeWithZone, ActiveSupport::TimeZone]

内容的提问来源于stack exchange,提问作者Aleksey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:06:03