2010-12-07 211 views
0

此代码工作正常。扩展类方法

class ArInvHeader < ActiveRecord 

    HUMANIZED_ATTRIBUTES = { 
    :shipto_customer_address => _("Ship to customer address ") 
    } 

    def self.human_attribute_name(attr,options={}) 
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super 
    end 

end 

我想把这个方法的共同文件,并在每一个模型中使用它。

def self.human_attribute_name(attr,options={}) 
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super 
end 

我该怎么做?

回答

2

我猜你想使用human_attribute_nameActiveRecord::Base所有子类使用它 - 如果是这样的话,这只是延长ActiveRecord::Base这个方法的问题,这样它就可以用于它的所有子类:只需打开类,定义方法,然后你就可以去:

class ActiveRecord::Base 

    def self.human_attribute_name(attr,options={}) 
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super 
    end 

end 

只需将其放在config/initializers/active_record.rb上,应用程序就会自动需要它。

或者,你可以使用目前的国际化工具轨道,实现了类似的结果 - 假设你的locale是en

# config/locales/en.yml 
en: 
    activerecord: 
    attributes: 
     ar_inv_header: 
     shipto_customer_address: "Ship to customer address " 

这样的话,你可以叫ArInvHeader.human_attribute_name(:shipto_customer_address)。这是更改ActiveRecord模型和属性的“人名”的首选方法。

+0

是的,我做了同样的事情,它工作正常。但是它是一个首选的方法吗? – 2010-12-07 22:23:07

0

您是否尝试过locale.yml这个功能?

+0

我需要修改它吗? – 2010-12-07 20:27:58

0

你可以把它放在你application_controller并使用此行:

helper_method :human_attribute_name 

现在你可以在整个系统