跳至内容 跳至搜索

Action Text RichText

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!"
方法
T

实例公共方法

to_plain_text()

返回 body 属性,其中所有 HTML 标记均已删除,为纯文本。

message = Message.create!(content: "<h1>Funny times!</h1>")
message.content.to_plain_text # => "Funny times!"
# File actiontext/app/models/action_text/rich_text.rb, line 37
def to_plain_text
  body&.to_plain_text.to_s
end

to_trix_html()

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

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 53
def to_trix_html
  body&.to_trix_html
end