Apr6

Rails Tip: Overriding Defaults in ActiveRecord

Have you ever wish you could tell Rails the name of the table that mapped to your model class?  Perhaps you want a model to represent a legacy table (which could be any table that already exists which is either too painful to recreate or over which you have no control).  Or perhaps you just want to be strange and call your class “This” and your table “that” (not something I’d recommend, but if you must satisfy that urge, you can).  Here’s how:

class Customer < ActiveRecord::Base
set_table_name "customp"
end

Now Rails will look for the table called “customp” when persisting or reading instances of Customer.  You can also use the more direct form:

class Customer < ActiveRecord::Base
self.table_name = "customp"
end

This tip comes from page 282 of the Rails book.


No Responses to “Rails Tip: Overriding Defaults in ActiveRecord”

You can leave a response, or trackback from your own site.

 

Leave a Reply

You must be logged in to post a comment.

 

Recent Posts

Popular Categories

Grails Mac Rails Bible Code Coffee Candor

About

I’m a software engineer by day and even busier by night.  This blog contains my thoughts on subjects from the Bible to lines of code.  I write (and drink) Java, I’m learning Ruby and Rails and I read the King James Bible.  I’m hoping to move the country and buy a farm and stay home with my family to bring them up in the nurture and admonition of the Lord.