модуль ActionText::Attribute
Публичные методы экземпляра
# File actiontext/lib/action_text/attribute.rb, line 33
def has_rich_text(name, encrypted: false)
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
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, вы можете использовать именованный скоуп:
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 * <tt>:encrypted</tt> - Pass true to encrypt the rich text attribute. The encryption will be non-deterministic. See +ActiveRecord::Encryption::EncryptableRecord.encrypts+. Default: false.
# File actiontext/lib/action_text/attribute.rb, line 61
def rich_text_association_names
reflect_on_all_associations(:has_one).collect(&:name).select { |n| n.start_with?("rich_text_") }
end # File actiontext/lib/action_text/attribute.rb, line 57 def with_all_rich_text eager_load(rich_text_association_names) end
Ускоренная загрузка всех зависимых моделей RichText оптом.
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.