Rails - Easily Work With Uppercase Column Names
Join the DZone community and get the full member experience.
Join For FreeI 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
Column (database)
Opinions expressed by DZone contributors are their own.
Trending
-
VPN Architecture for Internal Networks
-
Mastering Time Series Analysis: Techniques, Models, and Strategies
-
Front-End: Cache Strategies You Should Know
-
Apache Kafka vs. Message Queue: Trade-Offs, Integration, Migration
Comments