ruby-on-rails - Rails 覆盖验证器消息

标签 ruby-on-rails validation message

我有一个提供两种口味的网站:英语和法语。这是一些代码

app/views/user/register.html.erb
-----------------          
<% form_for .....>
  <%= f.text_field :first_name %> 
<% end %>

app/models/user.rb
------------------
class User < ActiveRecord::Base
  validates_presence_of :first_name

end 

现在,如果该网站以法语版本提供服务,则要显示错误消息,我有

app/config/locales/fr.yml
-------------------------
  activerecord:
    errors:
      messages:
        empty: "ne peut pas être vide"

因此,如果有人没有填写名字,验证器将采用该字段的名称并附加用于空子句的自定义消息

"First name ne peut pas être vide"

这是不正确的,因为法语中的“名字”是“Prénom”,因此应该是

"Prénom ne peut pas être vide"

请有人建议一种实现所需结果的方法。

最佳答案

摘自 Rails 文档中 ActiveRecord::Error 类中的generate_full_methods...

Wraps an error message into a full_message format.

The default full_message format for any locale is "{{attribute}} {{message}}". One can specify locale specific default full_message format by storing it as a translation for the key :"activerecord.errors.full_messages.format".

Additionally one can specify a validation specific error message format by storing a translation for :"activerecord.errors.full_messages.[message_key]". E.g. the full_message format for any validation that uses :blank as a message key (such as validates_presence_of) can be stored to :"activerecord.errors.full_messages.blank".

Because the message key used by a validation can be overwritten on the validates_* class macro level one can customize the full_message format for any particular validation:

# app/models/article.rb class Article < ActiveRecord::Base

validates_presence_of :title, :message => :"title.blank"   end   #  

config/locales/en.yml en:

activerecord:
  errors:
    full_messages:
      title:
        blank: This title is screwed!

关于ruby-on-rails - Rails 覆盖验证器消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652173/

相关文章:

linux消息其他用户的终端: change text color?

ruby-on-rails - Rails 中的 validates_format_of (仅限数字、逗号和空格)

ruby-on-rails - 如何访问设计 token 授权注册 Controller ?

ruby-on-rails - 如何测试内容是否可见,而不是被 Capybara/Selenium 中的滚动条隐藏

ruby-on-rails - 未找到操作

json - 如何在 json 模式验证中验证枚举值?

javascript - Express Validator 来验证日期时间

c# - FluentValidation:使用 ValidationContext 进行验证

Erlang 多处理消息接收和发送

python - 如何在 Python 中从流追加到文件而不是覆盖