我们在 Rails 5.2 上使用活动文本的存档版本做了类似的事情。
宝石文件
gem 'actiontext', git: 'https://github.com/kobaltz/actiontext.git', branch: 'archive', require: 'action_text'
模型/文章.rb
class Article < ApplicationRecord
has_paper_tail
serialize :body, ActionText::Content
...
end
助手/trix_editor_helper.rb
require 'action_view/helpers/tags/placeholderable'
module TrixEditorHelper
mattr_accessor(:id, instance_accessor: false) { 0 }
# Returns a +trix-editor+ tag that instantiates the Trix JavaScript editor as well as a hidden field
# that Trix will write to on changes, so the content will be sent on form submissions.
#
# ==== Options
# * <tt>:class</tt> - Defaults to "trix-content" which ensures default styling is applied.
#
# ==== Example
#
# rich_text_area_tag "content", message.content
# # <input type="hidden" name="content" id="trix_input_post_1">
# # <trix-editor id="content" input="trix_input_post_1" class="trix-content" ...></trix-editor>
def trix_editor_tag(name, value = nil, options = {})
options = options.symbolize_keys
options[:input] ||= "trix_input_#{TrixEditorHelper.id += 1}"
options[:class] ||= "trix-content"
options[:data] ||= {}
options[:data][:direct_upload_url] = main_app.rails_direct_uploads_url
options[:data][:blob_url_template] = main_app.rails_service_blob_url(":signed_id", ":filename")
editor_tag = content_tag("trix-editor", "", options)
input_tag = hidden_field_tag(name, value, id: options[:input])
input_tag + editor_tag
end
end
module ActionView::Helpers
class Tags::TrixEditor < Tags::Base
include Tags::Placeholderable
delegate :dom_id, to: ActionView::RecordIdentifier
def render
options = @options.stringify_keys
add_default_name_and_id(options)
options['input'] ||= dom_id(object, [options['id'], :trix_input].compact.join('_')) if object
@template_object.trix_editor_tag(options.delete("name"), editable_value, options)
end
def editable_value
value&.try(:to_trix_html)
end
end
module FormHelper
def trix_editor(object_name, method, options = {})
Tags::TrixEditor.new(object_name, method, self, options).render
end
end
class FormBuilder
def trix_editor(method, options = {})
@template.trix_editor(@object_name, method, objectify_options(options))
end
end
end
然后我们从 cdn 安装了 trix 版本 1.1 并使用了标准的 trix-attachments.js 和直接上传。
如果可能,希望升级到 Rails 6 并保留这个概念。