Brian McQuay

+menu-


Class table inheritance in Ruby on Rails

In my previous post I wrote about trying to get class table inheritance working in Rails. I passed by the hack and went with the plugin which ended up not really working right. I revisited the class table inheritance hack and actually got it working. I pretty much just dumped that code into a plugin so all you have to do is:

spaghetti.rb
[source language=":ruby"]
class Spaghetti < Noodle
class_table_inheritance
end
[/source]

noodle.rb
[source language=":ruby"]
class Noodle < ActiveRecord::Base
end
[/source]

One thing that did trip me up at first was that the spaghettis table can’t have an ‘id’ column for a primary key or you end up with some strange stack overflow errors. The noodles table also needs a ‘type’ varchar column to store the class names of the rows its storing. Even pagination works when you explicitly state what tables you’re conditions are using as in:

[source language=":ruby"]
@spaghetti_pages, @spaghettis = paginate :spaghettis,
:conditions => [ "noodles.length_in_inches = (?)", 10],
:per_page => 10
[/source]

Download the class_table_inheritance plugin

  • GonzoTanuki

    Hi, i have a problem with the plugin.
    I have:

    table publication:
    id
    title
    author
    type

    table book:
    publication_id
    editor

    publication.rb
    class Publication

  • GonzoTanuki

    class Publication

  • GonzoTanuki

    sory, the minor signus is not allowed…
    i have this:

    publication.rb
    class Publication ‘inherits’ ActiveRecord::Base
    end

    book.rb
    class Book ‘inherits’ Publication
    class_table_inheritance
    end

    When i do, book/show or book/list only shows the attributes of Publication.
    There is something that i’m doing wrong???

    Thanks. Gonzalo

    Sory if my english is a little poor…

  • http://www.pracstrat.com Jordan

    I’m so appreciating this CTI lib. It works well in the Rails 2.02. Now I want to upgrade my rails to the latest version 2.3.5. The CTI can’t work well now. Rails 2.3.5 changes a lot. So ask help. Whether the author can upgrade this CTI lib? Thank you!

  • http://www.brianmcquay.com admin

    I have since abandoned using this plugin because it creates a lot of unforseen problems. Its my opinion that this is something that has to be built into the core for it to really work properly with everything. The problems I encountered far outweighed any benefit. I recommend just doing a normal has_one association and just calling the parent model methods and attributes using child.parent.method instead of using this class table inheritance.