# Mapping column names in legacy schemata

**URL:** <https://www.ruby-forum.com/t/mapping-column-names-in-legacy-schemata/93058>\
**Category:** Rails\
**Created:** [April 27, 2007, 1:22am UTC](https://www.ruby-forum.com/t/mapping-column-names-in-legacy-schemata/93058 "2007-04-27T01:22:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tilo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/ed8c4c/32.png) [@tilo](https://www.ruby-forum.com/u/tilo)\
**Post date:** [April 27, 2007, 1:22am UTC](https://www.ruby-forum.com/t/mapping-column-names-in-legacy-schemata/93058/1 "2007-04-27T01:22:49Z")

</div>

I have a legacy MySQL database with a weird naming convention - all  
table and column  
names have a prefix ‘\_’ , which is annoying, and some of the column  
names are misnomers.

I would like to apply a pre-defined mapping between MySQL column names  
and method  
names to be used in the Ruby class, without having the original column  
names being visible anymore.

how can I pre-define a static mapping of all (legacy) column names to  
different Class method names?

e.g.: given legacy schema:

Table \_fix has columns:  
\_job  
\_ change  
\_date  
\_effect

When defining the Ruby class, I’d like to do something like this:

class Fix \< ActiveRecord::Base  
self.table\_name = “\_fix”  
use\_mapping ( # imaginary construct…  
:\_job =\> “job\_id”,  
:\_change =\> “change\_id” ,  
:\_date =\> “date” ,  
:\_effect =\> “status”)

self.primary\_key = “job\_id”  
end

and want to access it like this:

Fix.find( id ).status = “partial fix”

which should acces the  
Is there a way to do this?

thanks

Tilo

---

<div class="post-metadata">

**Author:** ![tilo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/ed8c4c/32.png) [@tilo](https://www.ruby-forum.com/u/tilo)\
**Post date:** [April 27, 2007, 1:59am UTC](https://www.ruby-forum.com/t/mapping-column-names-in-legacy-schemata/93058/2 "2007-04-27T01:59:51Z")

</div>

On Apr 27, 2007, at 1:22 AM, tilo wrote:

> class Fix \< ActiveRecord::Base

> self.table\_name = “\_fix”  
> use\_mapping ( # imaginary construct…  
> :\_job =\> “job\_id”,  
> :\_change =\> “change\_id” ,  
> :\_date =\> “date” ,  
> :\_effect =\> “status”)

You could add this somewhere, for instance in environment.rb:

class ActiveRecord::Base  
def self.map\_column(legacy, nice)  
class\_eval \<\<-EOS  
def #{nice}  
#{legacy}  
end

```
     def #{nice}=(val)
       self.#{legacy} = val
     end
   EOS
 end

```

end

The usage is

class Model \< ActiveRecord::Base  
map\_column :\_job, :job\_id  
map\_column :\_change, :change\_id  
…  
end

You see the technique in case you prefer another kind of macro. BTW,  
that cannot be based on alias\_method because AR accessors are not  
defined by then.

– fxn
