ruby-on-railsruby-on-rails-6actiontext

Converting back to plain text when using ActionText


First let me say that I love what Rails 6 has to offer in ActionText. Unfortunately when I declare it for an attribute in something like a post model:

class Post < ApplicationRecord
  has_rich_text :body
end

I can't access the body's text anymore. It becomes an ActionText instance. I completely understand this is how this functionality works but there are times I need to pass the plain text of the body to other external methods. In my case I'm using the body in my meta-description tags with a gem called meta-tags. Doing so results in this error:

Expected a string or an object that implements #to_str

This is because what was before a plain text column becomes an AT instance:

=> #<ActionText::RichText id: 39, name: "body", body: #<ActionText::Content "<div class=\"trix-conte...">, record_type: "Post", record_id: 161, created_at: "2019-08-17 17:34:27", updated_at: "2019-08-17 17:34:27"> 

Seeing that it had getter methods attached with it I tried to do something like @post.body.body but this is actually

=> #<ActionText::Content "<div class=\"trix-conte...">

Also note that I've tried to create a method inside the post model but once has_rich_text is declared I no longer have original access to my body's text.

I'm not exactly sure how to:


Solution

  • So apparently ActionText instances have a method for retrieving plain text values with to_plain_text. All together it looks like this:

    @post.body => <div>This is my markup</div>
    @post.body.to_plain_text => This is my markup