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
相关产品推荐
相关产品推荐

