<?xml version="1.0"?>
<rss version="2.0">
<channel>
  <title>waelchatila.com - ruby tag</title>
  <link>http://waelchatila.com:80/tags/ruby/</link>
  <description>Notes on Software, Engineering and Science</description>
  <language>en</language>
  <copyright>Wael Chatila</copyright>
  <lastBuildDate>Thu, 11 Mar 2010 03:23:48 GMT</lastBuildDate>
  <generator>Pebble (http://pebble.sourceforge.net)</generator>
  <docs>http://backend.userland.com/rss</docs>
  
  
  <item>
    <title>Single Table Polymorphic Inheritance with ActiveRecords </title>
    <link>`</link>
    
      
        <description>
          Implementing a single table polymorphic inheritance in rails is dead easy. 

Simply do
&lt;div class=&#034;codeSample&#034;&gt;
class Fruit &lt; ActiveRecord::Migration
  def self.up
    create_table :persons do |t|
      t.column :type :string
      t.column :shape, :string
      t.timestamps
    end

  end

  def self.down
    drop_table :fruits
  end
end
&lt;/div&gt;
or if you a migrating...
&lt;div class=&#034;codeSample&#034;&gt;
class Fruit &lt; ActiveRecord::Migration
    def self.up
        add_column :fruits, :type, :string
    end

    def self.down
        remove_column :fruits, :type
    end
end
&lt;/div&gt;

Now, all you have to do is to create your sub-classes
&lt;div class=&#034;codeSample&#034;&gt;
class Fruit &lt; ActiveRecord::Base
    def calc_volume
       ...
    end
end

class Apple &lt; Fruit
    def calc_volume
       ...
    end
end

&lt;/div&gt;

Don&#039;t forget to put &lt;i&gt;Apple&lt;/i&gt; in a separate file by itself &lt;i&gt;apple.rb&lt;/i&gt; or else ruby will spit out an unconditional warning if you reference &lt;i&gt;Apple&lt;/i&gt; in your code with &lt;i&gt;Fruit::Apple&lt;/i&gt;
&lt;div class=&#034;codeSample&#034;&gt;
warning: toplevel constant Fruit referenced by Fruit::Apple

&lt;/div&gt;
&lt;p&gt;&lt;a href=&#034;`&#034;&gt;Read more...&lt;/a&gt;&lt;/p&gt;
        </description>
      
      
    
    
    
    <category>Web</category>
    
    <comments>http://waelchatila.com:80/2008/05/22/1211520420000.html#comments</comments>
    <guid isPermaLink="true">`</guid>
    <pubDate>Fri, 23 May 2008 05:27:00 GMT</pubDate>
  </item>
  
  </channel>
</rss>

