6

我正在将我的一个新闻应用程序升级到 Rails 6.0.0。在解决问题时,我在使用富文本时遇到了问题。我的应用程序指向富文本正文字段,而不是我现有的表格正文字段。

是否可以将现有的表格文本字段用于富文本,以便我可以在需要时编辑内容。与新帖子一样,我可以使用 action_text_rich_texts 表,但对于现有帖子,我想使用现有的表格正文字段。

4

2 回答 2

5

ActionText 的助手为您has_rich_text 定义了getter 和 setter 方法。

您可以再次重新定义该方法,使用read_attributebody为 ActionText 提供存储在表中的值:

class Post
  has_rich_text :body

  # Other stuff...
  
  def body
    rich_text_body || build_rich_text_body(body: read_attribute(:body))
  end
于 2019-12-01T23:55:01.720 回答
4

假设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 问题评论

于 2020-05-29T19:00:14.127 回答