gpt4 book ai didi

ruby-on-rails - 翻译 Rails 模型关联 - 不工作

转载 作者:数据小太阳 更新时间:2023-10-29 06:56:00 25 4
gpt4 key购买 nike

有人知道如何在 Rails 中翻译模型关联吗?

例如:我有一个Person模型,它可以有很多Phone。但是,一个人需要至少有一部电话。我无法翻译该验证。我能做的最好的是:

validates_presence_of :phones, :message => "At least one phone is required."

在我的 YAML 上,我替换了这一行以省略 %{attribute}:

format: ! '%{message}'

这样只显示我的消息,我避免显示未翻译的字段名称。

这让我很头疼,因为有些gems根本不允许我传递:message => "something describing the error",所以我想配置所有的错误信息通过我的 YAML。

此外,对于某些模型,我可以转换它们的属性,而对于其他模型,我不能。例如:

activerecord:  
attributes:
additional_info:
account_manager: "Manager"

这行得通。我可以在我的表格“经理”上看到。但是,当该字段出现错误时,Rails 会将其显示为 "Additional info account manager can't be blank"

我试过这个:

activerecord:          
errors:
models:
additional_info:
attributes:
account_manager: "Manager"

但运气不好。

我确实阅读了文档,但不知道为什么会这样。

最佳答案

以下是 Rails 4.1 的有效关键路径:

# Basic Attribute on Model
activerecord:
attributes:
#{model_class.model_name.i18n_key}:
#{attribute_name}:
"Localized Value"

# Attribute on Nested Model
activerecord:
attributes:
#{model_class.model_name.i18n_key}/#{association_name}:
#{attribute_name}:
"Localized Value"
#{association_name}:
#{attribute_name}:
"Fallback Localized Value"

因此,给定此模型(具有 :personi18n_key):

class Person
has_many :friends
end

你会有这些语言环境定义:

activerecord:
attributes:
person:
first_name:
"My Name"
person/friends:
first_name:
"My Friend's Name"
friends:
first_name:
"A Friend's Name"

如果你的模型是一个命名空间,例如:

class MyApp::Person
has_many :friends
end

i18n_key 变为 :my_app/person 并且您的 / key 开始磨损:

activerecord:
attributes:
my_app/person:
first_name:
"My Name"
my_app/person/friends:
first_name:
"My Friend's Name"
friends:
first_name:
"A Friend's Name"

关于ruby-on-rails - 翻译 Rails 模型关联 - 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9266496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com