Rails 5.2中如何用ActionText显示旧文章的description字段内容?
解决旧文章Description无法通过ActionText显示的问题
这个问题我之前帮朋友处理过,核心就是要把posts表中原有description字段的历史数据迁移到ActionText对应的存储表中。具体操作步骤如下:
1. 编写数据迁移Rake任务
因为你已经在模型里加了has_rich_text :description,此时调用post.description会指向ActionText的富文本对象,而不是原来的数据库字段,所以我们需要用read_attribute来获取旧字段的原始值。
在lib/tasks目录下新建文件migrate_old_descriptions.rake,内容如下:
namespace :posts do desc "Migrate old post descriptions to ActionText" task migrate_descriptions: :environment do Post.find_each do |post| # 跳过已经有ActionText内容或旧字段为空的记录 next if post.description.present? || post.read_attribute(:description).blank? # 将旧字段内容赋值给ActionText富文本属性 post.description = post.read_attribute(:description) post.save! puts "成功迁移文章##{post.id}的描述内容" end puts "所有旧数据迁移完成!" end end
2. 执行迁移任务
在终端运行这个Rake任务:
rails posts:migrate_descriptions
执行过程中会输出每个迁移成功的文章ID,完成后会提示迁移结束。
3. 验证迁移结果
打开Rails控制台,查询任意一篇旧文章,确认@post.description已经能正常显示原有的描述内容:
rails c post = Post.find(旧文章ID) puts post.description.to_s
4. 可选:删除旧字段(迁移完成后)
如果确认所有数据都迁移成功,可以删除posts表中原来的description字段。先创建迁移文件:
rails generate migration RemoveDescriptionFromPosts
编辑生成的迁移文件:
class RemoveDescriptionFromPosts < ActiveRecord::Migration[5.2] def change remove_column :posts, :description, :text end end
然后执行迁移:
rails db:migrate
注意事项
- 操作前一定要备份数据库,避免数据丢失
- 如果旧的
description字段包含HTML格式,ActionText会自动兼容处理,无需额外转换
内容的提问来源于stack exchange,提问作者Charlie
相关产品推荐
相关产品推荐

