8

I am upgrading one of my news app to Rails 6.0.0. While working around I got a problem using Rich Text. My app is pointing the rich text body field instead of the my existing table body field.

Is it possible to use the existing table text field for the rich text, so that I can edit the contents whenever I need it. Like for new posts I can use the action_text_rich_texts table but for the existing posts I want to use the existing table body field.

Santosh Aryal
  • 1,276
  • 1
  • 18
  • 41

2 Answers2

8

Assuming there's a content in your model and that's what you want to migrate, first, add to your model:

has_rich_text :content

Then create a migration

rails g migration MigratePostContentToActionText

Result:

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

Refer to this Rails Issue comment.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Richard
  • 118
  • 1
  • 6
6

ActionText's helper has_rich_text defines getter and setter methods for you.

You can redefine the body method again, providing ActionText with the value stored in the table using read_attribute:

class Post
  has_rich_text :body

  # Other stuff...
  
  def body
    rich_text_body || build_rich_text_body(body: read_attribute(:body))
  end
Artem Ignatiev
  • 331
  • 2
  • 6
  • 1
    Elegant solution! It should be `read_attribute(:body)` though. This solution has the advantage of progressively converting a huge database with old texts instead of weighing heavy on the DB during migration (possibly looping though thousands of entries). Thanks! – morgler Jun 23 '21 at 19:14
  • 1
    Thanks! I've updated the code to fix the typo – Artem Ignatiev Jun 25 '21 at 09:34