现有文本字段的 Rails 操作文本

San*_*yal 6 ruby ruby-on-rails-6 actiontext

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

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

Ric*_*ard 9

假设您的模型中有 acontent并且这就是您想要迁移的内容,首先,添加到您的模型中:

has_rich_text :content
Run Code Online (Sandbox Code Playgroud)

然后创建迁移

rails g migration MigratePostContentToActionText
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)

请参阅此Rails Issue 评论


Art*_*iev 6

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
Run Code Online (Sandbox Code Playgroud)