方法
实例公共方法
has_rich_text(name, encrypted: false, strict_loading: strict_loading_by_default) 链接
提供对从属 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 支持的编辑器发送的附件链接。这些附件使用 Active Storage 与 RichText
模型关联。
如果你希望预加载从属 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.
选项
-
:encrypted
- 传递 true 以加密富文本属性。加密将是非确定性的。参见ActiveRecord::Encryption::EncryptableRecord.encrypts
。默认值:false。 -
:strict_loading
- 传递 true 以强制严格加载。如果省略,strict_loading:
将设置为strict_loading_by_default
类属性的值(默认值为 false)。
源代码: 显示 | 在 GitHub 上
# 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
rich_text_association_names() 链接
源代码: 显示 | 在 GitHub 上
# 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() 链接
批量急加载所有依赖的 RichText
模型。
来源:显示 | 在 GitHub 上
# File actiontext/lib/action_text/attribute.rb, line 62 def with_all_rich_text eager_load(rich_text_association_names) end