-
-
Save 3014zhangshuo/f7b8653530fd93df7864fd2863c749c5 to your computer and use it in GitHub Desktop.
Rails Single Table Inheritance example
This file contains hidden or 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