Skip to content

Instantly share code, notes, and snippets.

@benalavi
Last active November 7, 2018 19:15
Show Gist options
  • Save benalavi/26ff9eff12c004245bc3d350eedc5045 to your computer and use it in GitHub Desktop.
Save benalavi/26ff9eff12c004245bc3d350eedc5045 to your computer and use it in GitHub Desktop.
require "logger"
require "sequel"
DB = Sequel.connect ENV["DATABASE_URL"], test: true, encoding: "utf-8"
# DB.logger = Logger.new($stdout)
require "sequel/plugins/class_table_inheritance"
module Sequel
module Plugins
module ClassTableInheritance
def self.configure(model, opts = OPTS)
SingleTableInheritance.configure model, opts[:key], opts
model.instance_exec do
@cti_models = [self]
@cti_tables = [table_name]
@cti_instance_dataset = @instance_dataset
@cti_table_columns = columns
@cti_table_map = opts[:table_map] || {}
@cti_alias = opts[:alias] || @dataset.first_source.to_s.to_sym
@cti_ignore_subclass_columns = opts[:ignore_subclass_columns] || []
end
end
end
end
end
Sequel.extension :migration
Sequel.migration do
up do
DB.create_schema :charts
DB.run "SET search_path TO #{DB.literal("charts")};"
create_table :artists do
primary_key :id
column :name, :text
end
create_table :albums do
primary_key :id
column :type, :text
column :title, :text
foreign_key :artist_id, :artists
end
create_table :sold_albums do
column :id, :integer
foreign_key [:id], :albums
end
end
end.apply(DB, :up)
DB.run "SET search_path TO #{DB.literal("public")};"
class Artist < Sequel::Model(Sequel[:charts][:artists])
one_to_many :sold_albums
end
class Album < Sequel::Model(Sequel[:charts][:albums])
plugin :class_table_inheritance,
key: :type,
table_map: {
SoldAlbum: Sequel[:charts][:sold_albums]
}
many_to_one :artist
end
class SoldAlbum < Album
end
artist = Artist.create \
name: "Artist"
album = SoldAlbum.create \
title: "Album",
artist_id: artist.id
puts artist.sold_albums_dataset.sql
puts artist.sold_albums
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment