Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple table inheritance Rails and activerecord

I'm trying to implement Multiple Table Inheritance with ActiveRecord. Looks like all the available gems are pretty old. Am I missing something? Is there any "native" way to implement this with activerecord? I'm using Rails 3.2.3 and activerecord 3.2.1

like image 831
user711643 Avatar asked Oct 21 '22 13:10

user711643


2 Answers

Rails 6.1+ delegated type

Rails 6.1 added a "native" way to implement Multiple Table Inheritance via delegated type.

See the corresponding PR for details.

With this approach, the "superclass" is a concrete class that is represented by its own table, where all the superclass attributes that are shared amongst all the "subclasses" are stored. And then each of the subclasses have their own individual tables for additional attributes that are particular to their implementation. This is similar to what's called multi-table inheritance in Django, but instead of actual inheritance, this approach uses delegation to form the hierarchy and share responsibilities.

like image 142
Marian13 Avatar answered Oct 27 '22 18:10

Marian13


Single Table Inheritance (where each Car and Truck share one database)

class Vehicle < ActiveRecord
end

class Car < Vehicle
end

class Truck < Vehicle
end

In your case you are not sharing the database but rather the functions. You should then write a module and include it in each model

class Car < ActiveRecord
  extend VehicleFinders
end

class Truck < ActiveRecord
  extend VehicleFinders
end

module VehicleFinders
  def find_purchased
    #...
  end
end

So in extend module's method are class method on that calling class.include module's methods are instance method for object of calling class

This might be a good read for you http://raysrashmi.com/2012/05/05/enhance-rails-models

like image 45
montrealmike Avatar answered Oct 27 '22 19:10

montrealmike