Rails报错:Formtastic::Util模块不存在html_safe方法
html_safe报错问题 嘿,我来帮你解决这个烦人的500错误!先理清楚你的问题场景:
你的使用场景
你用Formtastic写了这段日期输入框代码:
<%= f.input :open_date, :as => :string, :input_html => {:class => 'datepicker'}, :start_date => Date.today, label: 'OPEN' %>
同时在模型里加了必填验证:
validates :open_date, presence: true
但提交空字段时,直接触发了500服务器错误,报错核心信息是:
ActionView::Template::Error (undefined method `html_safe' for Formtastic::Util:Module Did you mea...
报错原因
这个问题大概率是Formtastic版本与你当前使用的Rails版本不兼容导致的。Formtastic内部的Util模块在部分版本中依赖html_safe方法,但如果版本不匹配,这个方法要么被移除,要么模块结构发生了变化,就会出现这种未定义方法的错误。
解决方案
给你几个靠谱的解决办法,按优先级推荐:
最稳妥:调整到兼容的Formtastic版本
先确认你的Rails版本,再对应选择兼容的Formtastic版本:- Rails 6.x → 推荐Formtastic 4.x版本
- Rails 5.x → 适配Formtastic 3.x或4.x
- Rails 4.x → 对应Formtastic 3.x
修改你的
Gemfile:# 举个例子,针对Rails 6.x的配置 gem 'formtastic', '~> 4.0'然后运行
bundle install更新依赖,重启服务器即可。临时救急:给Formtastic补全缺失方法
如果暂时不想调整版本,可以在项目中添加一个初始化文件来修补:
在config/initializers/formtastic_fix.rb中写入:module Formtastic module Util def self.html_safe(string) string.to_s.html_safe end end end这段代码会给缺失
html_safe方法的Formtastic::Util模块补上该方法,让它能正常处理文本转义逻辑。换种写法:使用Formtastic原生日期输入
你也可以尝试不用:as => :string,改用Formtastic自带的日期输入类型:<%= f.input :open_date, :as => :date, :input_html => {:class => 'datepicker'}, :start_date => Date.today, label: 'OPEN' %>不过要注意你的日期选择器插件是否能适配原生的
date输入类型。
验证修复效果
修改完成后重启服务器,再提交空字段的表单,应该就能正常显示“不能为空”的验证提示,而不会触发500服务器错误啦!
内容的提问来源于stack exchange,提问作者catmal

