Rails-i18n 国际化 初体验

在提交表单之后,如果模型validate不通过,会往@user.errors里加入失败信息,@user.save失败后重新渲染『new』时会展示错误提示。


Rails-i18n 国际化 初体验_第1张图片
错误提示

展示错误信息的模板:
app/views/shared/_error_messages.html.erb

<% if @user.errors.any? %>
    
The form contain <%= pluralize(@user.errors.count, "error") %> :(
    <% @user.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %> # 注: # 模板片段filename以下划线开头, # 通过 <%= render 'shared/error_messages' %> 插入到 app/views/users/new.html.erb 中

activemodel中的错误信息处理:
/Users/cbd/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.6/lib/active_model/errors.rb

def full_messages
  map { |attribute, message| full_message(attribute, message) }
end

# Returns all the full error messages for a given attribute in an array.
#
#   class Person
#     validates_presence_of :name, :email
#     validates_length_of :name, in: 5..30
#   end
#
#   person = Person.create()
#   person.errors.full_messages_for(:name)
#   # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]

# Returns a full message for a given attribute.
#
#   person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
def full_message(attribute, message)
  return message if attribute == :base
  attr_name = attribute.to_s.tr('.', '_').humanize
  attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
  I18n.t(:"errors.format", {
    default:  "%{attribute} %{message}",
    attribute: attr_name,
    message:   message
  })
end

app/models/user.rb

## 密码验证
validates :password,length: {minimum: 6, message: "密码最少六位"}

# 这里的message就是长度验证失败时的错误信息
# 效果如上图

关于『Name,Email,Password』字样如何自定义为合适的中文,这里就要用到国际化的gem了——rails-i18n。

配置 config/application.rb

# 国际化
# # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :zh

新建文件 config/locales/zh.yml

zh:
  activerecord:
    attributes:
      user:
        name: "帐号"
        email: "邮箱"
        password: "密码"
        password_confirmation: "重复密码"
    errors:
      models:
        user:
          attributes:
            name:
              blank: "不得为空"
            email:
              blank: "不得为空"
            password:
              blank: "不得为空"
Rails-i18n 国际化 初体验_第2张图片
缺少的翻译会有提示
Rails-i18n 国际化 初体验_第3张图片

你可能感兴趣的:(Rails-i18n 国际化 初体验)