Rails中如何禁用.yml文件自动插值并处理属性名大小写
解决Rails邮箱重复注册错误提示的两个问题
1. 移除自动属性插值
Rails默认会在ActiveRecord错误消息前自动拼接属性名(默认格式为%{attribute} %{message}),这是导致你配置的消息出现重复前缀的原因。推荐两种精准解决方式:
方式一:手动添加基础错误
在User模型中自定义验证逻辑,将错误添加到:base而非:email属性,这样就不会自动带上属性名前缀:class User < ApplicationRecord validate :check_unique_email private def check_unique_email if User.exists?(email: email.downcase) errors.add(:base, "Provided email address is already used") end end end方式二:全局修改错误消息格式(谨慎使用)
如果希望所有错误消息都去掉属性名前缀,修改config/locales/en.yml中的full_messages.format:en: active_record: errors: full_messages: format: "%{message}"
2. 将属性名转为小写
如果需要保留属性名在消息中但显示为小写,可通过以下两种方式实现:
方式一:修改属性名翻译
在en.yml中直接将email属性的翻译设为小写,覆盖Rails默认的首字母大写规则:en: active_record: attributes: user: email: "email" models: user: attributes: email: taken: "Provided %{attribute} address is already used"方式二:在验证中直接指定消息
在模型的唯一性验证里直接写好包含小写属性名的消息,跳过I18n插值的大写转换:class User < ApplicationRecord validates :email, uniqueness: { message: "Provided email address is already used" } end
内容的提问来源于stack exchange,提问作者Dominik Miśkiewicz
相关产品推荐
相关产品推荐

