Skip to content

Instantly share code, notes, and snippets.

@3014zhangshuo
Forked from ruckus/gist:3124445
Created October 31, 2017 01:14
Show Gist options
  • Save 3014zhangshuo/f7b8653530fd93df7864fd2863c749c5 to your computer and use it in GitHub Desktop.
Save 3014zhangshuo/f7b8653530fd93df7864fd2863c749c5 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