Forum: Ruby on Rails Downcasing Legacy Table Column Names

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
jamie (Guest)
on 2005-11-30 18:43
(Received via mailing list)
I'm looking for the simplest way to *automatically* downcase the
attribute names of Models mapped to legacy tables that use upper
case. eg:

class Workorder < ActiveRecord::Base
   set_table_name "WORKORDER"
end

which has "NAME" as an attribute can use "name" as an attribute.

currently:
workorder = Workorder.find(1)
workorder.NAME # => "workorder 1 name"

I want:
workorder.name # => "workorder 1 name"


Thanks,
Jamie
Rick (Guest)
on 2005-12-01 16:24
You can add a getter/setter for each attribute like:

class Workorder < ActiveRecord::Base
   set_table_name "WORKORDER"

  def name
    self.NAME
  end

  def name=(theName)
    self.NAME = theName
  end

end

I've never used this myself so I may have the syntax wrong.  However I
believe the concept is sound.  Although it is not "automatic" as you
would like.
jamie (Guest)
on 2005-12-01 16:56
(Received via mailing list)
I ended up overriding method_missing in an abstract Model class.
Since ActiveRecord::Base's method_missing is private, I ended up
copying the whole thing and putting the modified version in my
subclass. Basically, since I know the column names are upper case, I
just look to see if method_name.upcase is in the model's attributes
hash and if so, upcase! the method_name and pass it along.

I've documented this here:
http://blog.dangdev.com/articles/2005/11/30/active...
table-column-names

Looking forward to comments or a better way to do this. (What I would
really like is to convert the attributes to lower case as they are set.)

Jamie
jamie (Guest)
on 2005-12-01 19:11
(Received via mailing list)
Yeah, but I didn't want to hand code all those accessors--was looking
for an automatic way to deal with the problem.

Thanks,

Jamie
This topic is locked and can not be replied to.