Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Action Text for existing text field

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.

like image 679
Santosh Aryal Avatar asked Aug 29 '19 03:08

Santosh Aryal


2 Answers

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.

like image 128
Richard Avatar answered Oct 19 '22 01:10

Richard


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
like image 5
Artem Ignatiev Avatar answered Oct 19 '22 00:10

Artem Ignatiev