ActiveRecord验证...自定义字段名称

Dmi*_*ten 2 activerecord ruby-on-rails

我想修复一些我的网站生成的错误消息.这是问题所在:

class Brand < ActiveRecord::Base
    validates_presence_of :foo
    ...
end
Run Code Online (Sandbox Code Playgroud)

我的目标是发出消息"需要门票描述"而不是"需要Foo"或者可能不是空白,或者其他什么.

这是如此重要的原因是因为我们之前说过该字段是ticket_summary.这很好,服务器编码使用它,但现在由于疯狂疯狂的业务分析师已经确定ticket_summary是一个糟糕的名称,应该是ticket_description.现在我不一定希望我的数据库由用户对字段名称的要求驱动,特别是因为它们可以在没有功能更改的情况下频繁更改.

是否有提供此功能的机制?

澄清

:message =>似乎不是正确的解决方案,:消息会给我"Foo [message]"作为错误,我希望更改消息生成的字段名称,而不是实际的消息本身(虽然我会满足于不得不改变整个事情).

Dmi*_*ten 8

所以答案很简单......

限定

self.human_attribute_name(attribute) 并返回人类可读的名称:

def self.human_attribute_name(attribute)
    if attribute == :foo 
        return 'bar'
    end
end
Run Code Online (Sandbox Code Playgroud)

我当然会使用名字地图.那就是那个.

  • 很好,但是这个方法在 Rails 4 中有 2 个参数,可以这样做: def self. human_attribute_name(attribute_key_name, options = {}) case attribute_key_name when :FOO return "Bar" else return super(attribute_key_name, options) end end (2认同)

Har*_*tty 7

将其添加到您的config/locales/en.yml文件中:

en:
  activerecord:
    errors:

      # global message format 
      format: #{message}

      full_messages:
        # shared message format across models
        foo:
          blank: Ticket description is required

        # model specific message format
        brand:
          zoo:
            blank: Name is required
Run Code Online (Sandbox Code Playgroud)

现在更改验证消息以引用新的消息格式:

validates_presence_of :bar, :message => "Empty bar is not a good idea"
validates_presence_of :foo, :message => "foo.blank"
validates_presence_of :zoo, :message => "brand.zoo.blank"
Run Code Online (Sandbox Code Playgroud)

让我们试试代码:

b = Brand.new
b.valid?
b.errors.full_messages
#=> ["Ticket description is required", 
#     "Empty bar is not a good idea",
#     "Name is required"]
Run Code Online (Sandbox Code Playgroud)

如上所示,您可以在三个级别自定义错误消息格式.

1)全局用于所有ActiveRecord错误消息

  activerecord:
    errors:
      format: #{message}
Run Code Online (Sandbox Code Playgroud)

2)跨模型的共享错误消息

  activerecord:
    errors:
      full_messages:
        foo:
          blank: Ticket description is required
Run Code Online (Sandbox Code Playgroud)

3)特定于模型的消息

  activerecord:
    errors:
      full_messages:
        brand:
          zoo:
            blank: Name is required
Run Code Online (Sandbox Code Playgroud)