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

2023-09-08 18:50:48 作者:梦醒、一切成灰

我想解决了我的网站会产生一些错误消息。这里的问题是:

I would like to fix up some error messages my site generates. Here is the problem:

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

我的目标是做一个消息票证说明为必填项,而不是富是必需的,也可以不为空,或者别的什么东西。

My goal is to make a message "Ticket description is required" instead of "Foo is required" or may not be blank, or whatever.

的原因,这是非常重要的,因为可以说,previously领域是ticket_summary。这是伟大的,服务器是coded到使用,但现在由于疯狂,疯狂的业务分析已经确定ticket_summary是一个贫穷的名称,应该是ticket_description。现在,我并不希望有我的数据库通过为字段名的用户需求来驱动,特别是因为他们可以经常更改,恕不功能的变化。

The reason this is so important is because lets say previously the field was ticket_summary. That was great and the server was coded to use that, but now due to crazy-insane business analysts it has been determined that ticket_summary is a poor name, and should be ticket_description. Now I don't necessarily want to have my db be driven by the user requirements for field names, especially since they can change frequently without functionality changes.

有一个机制来提供这个了吗?

Is there a mechanism for providing this already?

要澄清

:消息=>似乎并没有被正确的解决方案,:​​邮件给我富[消息]的错误,我期待改变的消息产生的场名称,而不是实际的消息本身(虽然我将落户于具有改变整个事情)。

:message => does not seem to be the correct solution, :message will give me "Foo [message]" as the error, I am looking to change the messages generated field name, not the actual message itself (though I will settle for having to change the whole thing).

推荐答案

因此​​,答案是很简单...

So the answer was quite simple...

定义

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

self.human_attribute_name(attribute) and return the human readable name:

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

我会用,当然名称的地图。而这就是这一点。

I'd use a map of names of course. And thats that.