instance method has_rich_text

Ruby on Rails 7.1.6

Since v6.0.6

Available in: v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

has_rich_text(name, encrypted: false, strict_loading: strict_loading_by_default)

Provides access to a dependent RichText model that holds the body and attachments for a single named rich text attribute. This dependent attribute is lazily instantiated and will be auto-saved when it’s been changed. Example:

class Message < ActiveRecord::Base
  has_rich_text :content
end

message = Message.create!(content: "<h1>Funny times!</h1>")
message.content? #=> true
message.content.to_s # => "<h1>Funny times!</h1>"
message.content.to_plain_text # => "Funny times!"

The dependent RichText model will also automatically process attachments links as sent via the Trix-powered editor. These attachments are associated with the RichText model using Active Storage.

If you wish to preload the dependent RichText model, you can use the named scope:

Message.all.with_rich_text_content # Avoids N+1 queries when you just want the body, not the attachments.
Message.all.with_rich_text_content_and_embeds # Avoids N+1 queries when you just want the body and attachments.
Message.all.with_all_rich_text # Loads all rich text associations.

Options

  • :encrypted - Pass true to encrypt the rich text attribute. The encryption will be non-deterministic. See ActiveRecord::Encryption::EncryptableRecord.encrypts. Default: false.

  • :strict_loading - Pass true to force strict loading. When omitted, strict_loading: will be set to the value of the strict_loading_by_default class attribute (false by default).

Parameters

name req
encrypted key = false
strict_loading key = strict_loading_by_default
Source
# File actiontext/lib/action_text/attribute.rb, line 37
      def has_rich_text(name, encrypted: false, strict_loading: strict_loading_by_default)
        class_eval <<-CODE, __FILE__, __LINE__ + 1
          def #{name}
            rich_text_#{name} || build_rich_text_#{name}
          end

          def #{name}?
            rich_text_#{name}.present?
          end

          def #{name}=(body)
            self.#{name}.body = body
          end
        CODE

        rich_text_class_name = encrypted ? "ActionText::EncryptedRichText" : "ActionText::RichText"
        has_one :"rich_text_#{name}", -> { where(name: name) },
          class_name: rich_text_class_name, as: :record, inverse_of: :record, autosave: true, dependent: :destroy,
          strict_loading: strict_loading

        scope :"with_rich_text_#{name}", -> { includes("rich_text_#{name}") }
        scope :"with_rich_text_#{name}_and_embeds", -> { includes("rich_text_#{name}": { embeds_attachments: :blob }) }
      end

Defined in actiontext/lib/action_text/attribute.rb line 37 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionText::Attribute

Type at least 2 characters to search.

↑↓ navigate · open · esc close