You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7中如何本地化含ActiveModel::Model的表单对象属性错误消息?

Rails 7中ActiveModel::Model表单对象的属性本地化解决方法

你遇到的问题是因为ActiveModel::Model表单对象的本地化配置节点不是activerecord,而是activemodel。继承ApplicationRecord的模型用activerecord节点,但包含ActiveModel::Model的类需要对应到activemodel节点下配置。

正确的本地化配置

修改你的YAML文件,将配置从activerecord移到activemodel节点下:

en:
  activemodel:
    attributes:
      production_data_form:
        monitorable_type: "Post"

这样当monitorable_type为空时,错误消息就会显示为"Post can't be blank"。

自定义错误消息(可选)

如果需要更精细的错误消息控制,可以补充errors节点配置:

en:
  activemodel:
    attributes:
      production_data_form:
        monitorable_type: "Post"
    errors:
      models:
        production_data_form:
          attributes:
            monitorable_type:
              blank: "can't be blank"

核心原因

Rails将ActiveRecord(数据库模型)和ActiveModel(非数据库模型,如表单对象)的本地化配置分开管理:

  • activerecord节点:对应继承ApplicationRecord的数据库模型
  • activemodel节点:对应所有包含ActiveModel模块的对象(包括你的表单对象)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:59:50