You need to enable JavaScript to run this app. Rails 6 基于Formtastic创建自定义Editor.js输入组件的问题
优惠活动
大模型
产品
解决方案
定价
更多

Rails 6 基于Formtastic创建自定义Editor.js输入组件的问题

问题根因

  1. as: :hidden 不生效的原因:input_html_options 方法返回的是输入标签的HTML属性集合,as 是Formtastic用来声明输入组件类型的参数,不属于HTML属性,放在该方法中不会生效。
  2. 无法添加额外div的原因:自定义Formtastic输入组件的完整渲染逻辑由to_html方法控制,仅重写input_html_options只能修改输入标签本身的属性,无法追加额外的DOM元素。

正确实现代码

在Rails项目的app/inputs/editor_js_input.rb中写入以下代码:

class EditorJsInput < Formtastic::Inputs::HiddenInput
  # 重写渲染逻辑,拼接隐藏输入和editorjs容器
  def to_html
    super + template.content_tag(:div, '', 
      style: 'width: 100%; background: white;', 
      id: 'editorjs'
    )
  end

  # 仅修改隐藏输入的HTML属性
  def input_html_options
    super.merge(id: 'editor_field')
  end
end

注:直接继承Formtastic::Inputs::HiddenInput就会默认渲染隐藏类型的输入框,不需要额外设置as: :hidden。

调用方式

在ActiveAdmin的表单配置中直接调用即可,无需再渲染局部模版:

<%= f.input :body, as: :editor_js %>

可选优化(避免同一页面多编辑器冲突)

如果同一个页面需要使用多个Editor.js实例,不要写死id,改为动态生成:

class EditorJsInput < Formtastic::Inputs::HiddenInput
  def to_html
    super + template.content_tag(:div, '', 
      style: 'width: 100%; background: white;', 
      id: "editorjs_#{method}"
    )
  end

  def input_html_options
    super.merge(id: "editor_field_#{method}")
  end
end

对应的JS逻辑中根据字段名匹配对应的id即可。


内容的提问来源于stack exchange,提问作者mr_muscle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 03:36:03