在 Rails 中更改错误字段名称 [英] Change error field name in Rails

查看:33
本文介绍了在 Rails 中更改错误字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法更改与其关联的验证错误的字段名称.例如,如果我在没有任何数据的情况下提交名字(实际上是表中的 fname),它会大喊 Fname 不能为空.

I'm wondering if there's a way to change the field name for a validation error it's associated with. For example, if I submit First Name (really fname in the table) without any data, it yells Fname can't be blank.

是否可以将其更改为名字不能为空?

推荐答案

现在的一般做法是编辑您的 locals 像这样:

The general practice now-a-days is to edit your locals like so:

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        fname: "First Name"

您的错误消息现在将显示名字不能是..."

Your error message will now say "First Name can't be..."

为了完整起见,您还有另一种选择.这是将以下内容添加到您的用户模型中:

For completeness sake, you have another option. Which is to add the following to your User Model:

class User < ActiveRecord::Base

  HUMANIZED_ATTRIBUTES = {
    :fname => "First Name"
  }

  def self.human_attribute_name(attr, options = {}) # 'options' wasn't available in Rails 3, and prior versions.
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end

这篇关于在 Rails 中更改错误字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆