跳至内容 跳至搜索

Action Text RichText

The RichText 记录保存了由 Trix 编辑器生成的序列化 body 属性中的内容。它还保存了对所有嵌入文件的引用,这些文件使用 Active Storage 存储。然后将此记录与应用程序希望拥有富文本内容的 Active Record 模型相关联,使用 has_rich_text 类方法。

class Message < ActiveRecord::Base
  has_rich_text :content
end

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

message = Message.create!(content: "<div onclick='action()'>safe<script>unsafe</script></div>")
message.content #=> #<ActionText::RichText....
message.content.to_s # => "<div>safeunsafe</div>"
message.content.to_plain_text # => "safeunsafe"
方法
E
R
T

实例公共方法

embeds

返回嵌入文件的 ActiveStorage::Blob

# File actiontext/app/models/action_text/rich_text.rb, line 52
has_many_attached :embeds

record

返回关联的记录。

# File actiontext/app/models/action_text/rich_text.rb, line 46
belongs_to :record, polymorphic: true, touch: true

to_plain_text()

返回 body 属性中包含的标记的纯文本版本,标签已删除但 HTML 实体已编码。

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

注意:返回的字符串不是 HTML 安全的,不应在浏览器中呈现。

message = Message.create!(content: "&lt;script&gt;alert()&lt;/script&gt;")
message.content.to_plain_text # => "<script>alert()</script>"
# File actiontext/app/models/action_text/rich_text.rb, line 69
def to_plain_text
  body&.to_plain_text.to_s
end

to_s

安全地将 RichText 转换为 HTML String

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

message = Message.create!(content: "<div onclick='action()'>safe<script>unsafe</script></div>")
message.content.to_s # => "<div>safeunsafe</div>"
# File actiontext/app/models/action_text/rich_text.rb, line 39
serialize :body, coder: ActionText::Content

to_trix_html()

以可在 Trix 编辑器中编辑的格式返回 body 属性。附件的预览将内联呈现。

content = "<h1>Funny Times!</h1><figure data-trix-attachment='{\"sgid\":\"..."\}'></figure>"
message = Message.create!(content: content)
message.content.to_trix_html # =>
# <div class="trix-content">
#   <h1>Funny times!</h1>
#   <figure data-trix-attachment='{\"sgid\":\"..."\}'>
#      <img src="http://example.org/rails/active_storage/.../funny.jpg">
#   </figure>
# </div>
# File actiontext/app/models/action_text/rich_text.rb, line 85
def to_trix_html
  body&.to_trix_html
end