Improving Single Table Inheritance in Rails

Posted by Lance Ivy Thu, 26 Jul 2007 19:11:00 GMT

I started digging into STI recently and noticed people wondering how to restrict which attributes apply to which subclass. The general attitude seems to be that you just don’t – STI is meant for differences in behavior. Well I don’t completely buy, since I definitely have an is_a? situation here just crying out for model subclassing. And I also believe in locking down the data model as much as possible, and I want self-documenting code that tells people which attributes are intended for which subclass. So I scoped out the situation and came up with the following simple ActiveRecord::Base patch:

> lib/activerecord_unused_attributes.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class ActiveRecord::Base
  class << self
    def set_unused_columns(*columns)
      @unused_columns = columns.collect {|c| c.to_sym}
    end
    def unused_columns
      @unused_columns || []
    end

    def columns_with_unused_columns
      unless @columns
        @columns = columns_without_unused_columns.reject {|c| unused_columns.include? c.name.to_sym}
      end
      @columns
    end
    alias_method_chain :columns, :unused_columns
  end
end

I’m sure this could be improved, and anyone is welcome to do so. But anyhow, make sure to require the file from your environment.rb, then use it like this:

example usage
class ParentClass < ActiveRecord::Base
end

class MySubClass < ParentClass
  set_unused_columns :some_column, :some_other_column
end

Posted in ,  | Tags  | no comments

Comments

(leave url/email »)

   Comment Markup Help Preview comment