carbonr
carbonr

Reputation: 6067

Override active record column names to uppercase

I'm trying to make the active record column names to upper case by default by override the active record connection adapter for mysql. but im definitely doing something wrong and getting missing attribute errors.

I have to do this because we have a complicated setup where we switch between oracle and MySQL and both the databases use uppercase tables names and column names.

This is how i have tried but it doesn't seem to work

module ActiveRecord::ConnectionAdapters
    class Column
        def name
            @name.downcase
        end
    end
end

can someone suggest what is wrong here.

Upvotes: 0

Views: 1031

Answers (1)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42799

I wouldn't do it on the ActiveRecord class it self, you'll probably end up breaking a lot of built in functions in rails it self.

Also you should understand that calling an attribute of a class within the class it self will case an infinite recursive call and end up with an error

class Something < ActiveRecord::Base
  def name
    name.downcase # this is bad
  end
end

Instead you should use the function read_attribute

class Something < ActiveRecord::Base
  def name
    read_attribute(name).downcase # this will work safely
  end
end

And if you want to keep your code clean and not repeat the same thing every where, you could extract this to a concern and include it inside the classes you want to use this.

module DownCaseName
  extend ActiveSupport::Concern
  def name
    read_attribute(name).downcase
  end
end

class Something < ActiveRecord::Base
  incude DownCaseName
end

Upvotes: 1

Related Questions