gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:01:09 25 4
gpt4 key购买 nike

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

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/

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