I’m using a legacy database that has tables with column names that are UPPER\CASE. What I’d like is to have the UPPER\_CASE column names inserted as lower\_case attribute keys so that I can use _model.some\_attribute instead of model.SOME\_ATTRIBUTE. Instead, I found that I could override method\_missing in ActiveRecord::Base to check for the UPPER\CASE version of _some\_attribute. Since the method is private, I had to copy the whole thing. I put it into a base class that my models inherit from. All the modification does is check if the method\_name.upcase is in the attributes hash. If so, it upcases the method\_name and uses that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class AbstractLegacyModel < ActiveRecord::Base def method_missing(method_id, *args, &block) method_name = method_id.to_s # the next line is new code: method_name.upcase! if @attributes.include?(method_name.upcase) if @attributes.include?(method_name) define_read_methods if self.class.read_methods.empty? && self.class.generate_read_methods read_attribute(method_name) elsif self.class.primary_key.to_s == method_name id elsif md = /(=|\?|_before_type_cast)$/.match(method_name) attribute_name, method_type = md.pre_match, md.to_s # next line is new code attribute_name.upcase! if @attributes.include?(attribute_name.upcase) if @attributes.include?(attribute_name) case method_type when '=' write_attribute(attribute_name, args.first) when '?' query_attribute(attribute_name) when '_before_type_cast' read_attribute_before_type_cast(attribute_name) end else super end else super end end end |
I’m not sure if this will work across the board, so I’ve got to write some tests to cover this.
It would be great if rails would automatically downcase table column names, so I put in a feature request for that today.
Posted by jamieorc
Posted by jamieorc
Posted by jamieorc