Last active
November 6, 2018 01:04
-
-
Save benalavi/35429576f87c1bd675e81bc19fb80174 to your computer and use it in GitHub Desktop.
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
require "logger" | |
require "sequel" | |
DB = Sequel.connect ENV["DATABASE_URL"], test: true, encoding: "utf-8" | |
DB.logger = Logger.new($stdout) | |
Sequel.extension :migration | |
Sequel.migration do | |
up do | |
create_table :releases do | |
primary_key :id | |
column :title, :text | |
end | |
create_table :tracks do | |
primary_key :id | |
foreign_key :release_id, :releases, null: false | |
column :title, :text | |
end | |
end | |
end.apply(DB, :up) | |
class Release < Sequel::Model | |
plugin :nested_attributes | |
one_to_many :tracks | |
nested_attributes :tracks | |
end | |
class Track < Sequel::Model | |
many_to_one :release | |
def validate | |
puts "Track validate #{associations[:release]&.object_id}" | |
end | |
def before_save | |
puts "Track before_save #{associations[:release]&.object_id}" | |
end | |
end | |
puts "Creation w/ nested_attributes" | |
Release.create \ | |
title: "Release", | |
tracks_attributes: [{ | |
title: "Track" | |
}] | |
puts | |
puts "Creation using adder w/ given reciprocal reference" | |
release = Release.create \ | |
title: "Release" | |
puts "Release id: #{release.object_id}" | |
release.add_track \ | |
release: release, | |
title: "Track" | |
puts | |
puts "Lots of queries" | |
class Track < Sequel::Model | |
def validate | |
super | |
errors.add :title, "should not be the same as the release title for whatever reason" if title == release.title | |
puts "Track validate #{associations[:release]&.object_id}" | |
end | |
end | |
Release.create \ | |
title: "Release", | |
tracks_attributes: 100.times.collect{ |i| { title: "Track #{i}" } } | |
puts | |
puts "Loads association given id" | |
release = Release.create \ | |
title: "Release" | |
Track.create \ | |
release: nil, | |
release_id: release.id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment