我有具有特殊验证的属性,我使用消息子句来显示专门用于该验证的特殊消息。这是一个例子:
validates :email, presence: true, length: { maximum: 60 },
format: { with: valid_email_regex, message: "is not a valid email address format." },
uniqueness: { case_sensitive: false }
我想翻译这里的消息,但我不知道该怎么做。
我见过一些例子,他们输入这样的内容:message: t("some_value_here")。我不确定这个名称。我尝试了类似这样的消息:t(:bad_email)。我在 yaml 文件中执行了以下操作只是为了尝试一些操作。
activemodel:
errors:
bad_email: "is not a valid email address format."
当我尝试访问我的 Rails 应用程序时,出现以下错误:
ActionView::Template::Error (undefined method `t' for #<Class:0x007fefc1b709e0>)
我也在我的 yaml 文件中尝试过这个:
activemodel:
errors:
user:
bad_email: "is not a valid email address format."
我一整天都在断断续续地研究这个问题。我能找到的就是替换内置错误哈希,例如空白或空。有没有办法让我拥有自定义错误哈希并在模型中替换它们?此时我无法让 t 按编码工作。我希望问题在于我如何设置 yaml 文件。我见过不同版本的设置方法。我不确定是否应该将其放在 activemodel 或 activerecord 下。我假设是 activemodel,因为那是我想要翻译的自定义消息的地方。
如有任何帮助,我们将不胜感激。这是我在启动应用程序的第一个翻译之前需要弄清楚的最后一个部分。
更新 2013 年 7 月 29 日晚上 7:30 CDT
bgates 为我提供了一个很好的开始,让我了解如何设置模型文件以接收 YAML 文件中的自定义消息。不过,我最终必须在 yaml 文件中进行以下设置才能找到自定义消息。
activerecord:
errors:
models:
user:
attributes:
bio:
no_links: "cannot contain email addresses or website links (URLs)."
email:
bad_email: "is not a valid email address format."
username:
bad_username: "can only contain numbers and letters. No special characters or spaces."
最佳答案
使用消息符号:
validates :email, presence: true, length: { maximum: 60 },
format: { with: valid_email_regex, message: :bad_email },
uniqueness: { case_sensitive: false }
然后在yaml文件中
[lang]:
activerecord:
errors:
messages:
bad_email: "just ain't right"
如果有特定于该模型的翻译,它将覆盖上面的通用翻译:
[lang]:
activerecord:
errors:
models:
model_name: # or namespace/model_name
attributes:
email:
bad_email: "model-specific message for invalid email"
如果您编写自定义验证,add_error(:email, :bad_email)
将执行上面的查找,但是 errors[:email] << :bad_email
不会。
关于ruby-on-rails - Ruby on Rails i18n - 想要翻译模型中的自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935597/