Spec-Zone.ru › Ruby on Rails 7.1

модуль ActionText::Attribute

Публичные методы экземпляра

has_rich_text(name, encrypted: false, strict_loading: strict_loading_by_default) Показать исходный код
# 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

Обеспечивает доступ к зависимой модели RichText, которая хранит тело и вложения для одного именованного атрибута форматированного текста. Этот зависимый атрибут создается лениво и будет автоматически сохранен после изменения. Пример:

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!"

Зависимая модель RichText также будет автоматически обрабатывать ссылки на вложения, отправленные через редактор на базе Trix. Эти вложения связаны с моделью RichText с помощью Active Storage.

Если вы хотите предварительно загрузить зависимую модель RichText, вы можете использовать именованный 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.

Параметры

  • :encrypted - Установите true, чтобы зашифровать атрибут форматированного текста. Шифрование будет недетерминированным. См. ActiveRecord::Encryption::EncryptableRecord.encrypts. По умолчанию: false.

  • :strict_loading - Установите true, чтобы принудительно загрузить строго. Если опущено, strict_loading: будет установлено в значение атрибута класса strict_loading_by_default (по умолчанию false).

rich_text_association_names() Показать исходный код
# File actiontext/lib/action_text/attribute.rb, line 66
def rich_text_association_names
  reflect_on_all_associations(:has_one).collect(&:name).select { |n| n.start_with?("rich_text_") }
end
with_all_rich_text() Показать исходный код
# File actiontext/lib/action_text/attribute.rb, line 62
def with_all_rich_text
  eager_load(rich_text_association_names)
end

Нетерпеливая загрузка всех зависимых моделей RichText оптом.

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API