Skip to content

Instantly share code, notes, and snippets.

@ruckus
Created July 16, 2012 19:11
Show Gist options
  • Save ruckus/3124445 to your computer and use it in GitHub Desktop.
Save ruckus/3124445 to your computer and use it in GitHub Desktop.
Rails Single Table Inheritance example
create_table :media_items do |t|
t.string :type, :null => false, :limit => 32
t.string :name
t.timestamps
end
class MediaItem < ActiveRecord::Base
validates_presence_of :kind
end
class Post < MediaItem
# requires a :type attribute = 'Post'
end
class Folder < MediaItem
# requires a :type attribute = 'Folder'
end
# Create some entries
Post.new(:name => "How to Win At Poker") # translates to an INSERT INTO media_items ...
Folder.new(:name => "public_documents")
# Fetch some entries
Post.where(:name => "Travelling in Costa Rica")
# translates to SELECT * FROM media_items where type = "Post" and name = "Travelling in Costa Rica"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment