Rails - Easily work with uppercase column names

我们在Oracle建的表和字段名字基本上是大写的。这对我们是非常有用的。
I had to work with a legacy database with hundreds of tables with uppercase column names. Here is how I made my life a whole lot easier...
[code]
module ActiveRecord
class MyCustomARClass < ActiveRecord::Base

def self.reloadable?
false
end

# all columns are uppercase
set_primary_key 'ID'

# convert to uppercase attribute if in existence
# record.name => record.NAME
# record.id => record.ID
def method_missing(method_id, *args, &block)
method_id = method_id.to_s.upcase if @attributes.include? method_id.to_s.upcase.gsub(/=/, '')
super(method_id, *args, &block)
end

# strip leading and trailing spaces from attribute string values
def read_attribute(attr_name)
value = super(attr_name)
value.is_a?(String) ? value.strip : value
end

class << self # Class methods

private
# allow for find_by and such to work with uppercase attributes
# find_by_name => find_by_NAME
# find_by_dob_and_height => find_by_DOB_and_HEIGHT
def extract_attribute_names_from_match(match)
match.captures.last.split('_and_').map { |name| name.upcase }
end
end
end
end[/code]


This was defined in a plugin. Then, in each of my models I used the subclass instead of ActiveRecord::Base, like so...

[code]class MyModel < ActiveRecord::MyCustomARClass
# ...
end[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值