Rails Tip: Overriding Defaults in ActiveRecord
Categories: Code, RailsHave 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.
Leave a Reply
You must be logged in to post a comment.