现有文本字段的Rails Action Text

9

我正在将我的新闻应用程序升级到Rails 6.0.0。在处理过程中,我遇到了使用“富文本”时的问题。我的应用程序指向富文本正文字段而不是我的现有表正文字段。

是否可能使用现有的表格文本字段来进行富文本编辑,以便我可以随时编辑内容。例如,对于新文章,我可以使用action_text_rich_texts表,但对于现有文章,我希望使用现有的表格正文字段。

2个回答

9

假设你的模型中有一个 content 字段,这是你要迁移的内容。首先,在你的模型中添加:

has_rich_text :content

然后创建一个迁移

rails g migration MigratePostContentToActionText

结果:

class MigratePostContentToActionText < ActiveRecord::Migration[6.0]
  include ActionView::Helpers::TextHelper
  def change
    rename_column :posts, :content, :content_old
    Post.all.each do |post|
      post.update_attribute(:content, simple_format(post.content_old))
    end
    remove_column :posts, :content_old
  end
end

请参考这个Rails问题评论


6

ActionText的helper has_rich_text 定义了获取和设置方法,帮助你管理富文本。

你可以重新定义body方法,使用read_attribute提供的存储在表格中的值来更新ActionText:

class Post
  has_rich_text :body

  # Other stuff...
  
  def body
    rich_text_body || build_rich_text_body(body: read_attribute(:body))
  end

1
优雅的解决方案!不过应该是 read_attribute(:body)。这个解决方案具有逐步转换旧文本的巨大数据库的优势,而不是在迁移期间对数据库造成沉重负担(可能需要循环遍历数千条记录)。谢谢! - morgler
1
谢谢!我已经更新了代码以修复拼写错误。 - Artem Ignatiev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接