Skip to content

Instantly share code, notes, and snippets.

@benalavi
Last active December 13, 2018 17:56
Show Gist options
  • Save benalavi/20817b785a08d16912f82ce31afde029 to your computer and use it in GitHub Desktop.
Save benalavi/20817b785a08d16912f82ce31afde029 to your computer and use it in GitHub Desktop.
require "sequel"
DB = Sequel.sqlite
DB.create_table :albums do
primary_key :id
column :title, :text
end
DB.create_table :artists do
primary_key :id
foreign_key :album_id, :albums, null: false
column :name, :text
end
DB.create_table :covers do
primary_key :id
foreign_key :album_id, :albums, null: false
column :color, :text
end
class Album < Sequel::Model
plugin :nested_attributes
one_to_many :artists
nested_attributes :artists
one_to_one :cover
nested_attributes :cover
end
class Artist < Sequel::Model
many_to_one :album
def validate
puts "#{self} validate #{album}"
super
errors.add :name, "cannot be album name" if name == album.title
end
def after_save
puts "#{self} after_save #{album}"
album.title
end
end
class Cover < Sequel::Model
many_to_one :album
def validate
puts "#{self} validate #{album}"
super
errors.add :color, "cannot be album name" if color == album.title
end
def after_save
puts "#{self} after_save #{album}"
album.title
end
end
puts "create Album + one_to_many Artist + one_to_one Cover"
Album.create \
title: "Album 1",
artists_attributes: [{
name: "Bill"
}],
cover_attributes: {
color: "Red"
}
puts "create Album"
album = Album.create \
title: "Album 2"
puts "update Album + one_to_many Artist"
album.update \
artists_attributes: [{
name: "Steve"
}]
puts "update Album + one_to_one Cover"
album.update \
cover_attributes: {
color: "Blue"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment