Created
July 16, 2012 19:11
-
-
Save ruckus/3124445 to your computer and use it in GitHub Desktop.
Rails Single Table Inheritance example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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