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...
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



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

class MyModel < ActiveRecord::MyCustomARClass
  # ...
end

你可能感兴趣的:(Rails,ActiveRecord,Oracle)