ActiveRecordvalidation…自定义字段名称

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

class Brand < ActiveRecord::Base validates_presence_of :foo ... end 

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

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

是否有提供此function的机制?

澄清

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

将其添加到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 

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

 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" 

让我们试试代码:

 b = Brand.new b.valid? b.errors.full_messages #=> ["Ticket description is required", # "Empty bar is not a good idea", # "Name is required"] 

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

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

  activerecord: errors: format: #{message} 

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

  activerecord: errors: full_messages: foo: blank: Ticket description is required 

3)特定于模型的消息

  activerecord: errors: full_messages: brand: zoo: blank: Name is required 

所以答案很简单……

限定

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

 def self.human_attribute_name(attribute) if attribute == :foo return 'bar' end end 

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

你可以这样做:

 # config/locales/en.yml en: activerecord: attributes: brand: foo: "Ticket description" errors: models: brand: attributes: foo: blank: " is required" 

有关更多详细信息,请使用Rails检查完全自定义validation错误消息 。