Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding "Single Table Inheritance" in Rails/ActiveRecord and Legacy Schema

I am trying to integrate with a Legacy table that has a column named "type".

Rails will "smartly" assume that whenever we have a 'type' column in a table, then it will try to use Single Table Inheritance.

Is there anyway to avoid this?

(I can't rename the column).

like image 244
iwan Avatar asked Jul 08 '10 06:07

iwan


2 Answers

Well, most of the type it really is smart - convention over configuration has some very real benefits. ;-)

Where convention doesn't work, as in your case, there is (probably - at least, I've always found one so far...) a way around it. For legacy schemas there are a couple of possibilities that spring immediately to mind.

  • Create a single-table view in your legacy database that remaps columns to avoid AR's conventional names. Not much use if you don't have CREATE VIEW permissions on the DB, of course, or if your DB doesn't have views;
  • Override the use of :type as the STI indicator using set_inheritance_column, thus

class LegacyValue < ActiveRecord::Base
  set_inheritance_column 'does_not_have_one'
end
like image 147
Mike Woodhouse Avatar answered Oct 11 '22 06:10

Mike Woodhouse


In Rails 4 set_inheritance_column is deprecated and self.inheritance_column should be used instead:

class LegacyValue < ActiveRecord::Base
  self.inheritance_column = 'does_not_have_one'
end
like image 2
user3443285 Avatar answered Oct 11 '22 08:10

user3443285