Skip to content

Instantly share code, notes, and snippets.

@solnic
Created September 15, 2017 16:07
Show Gist options
  • Save solnic/77ac65fa190a43cf1cbe1defa2390444 to your computer and use it in GitHub Desktop.
Save solnic/77ac65fa190a43cf1cbe1defa2390444 to your computer and use it in GitHub Desktop.
require 'rom'
require 'rom-repository'
require 'rom-sql'
require 'logger'
config = ROM::Configuration.new(:sql, 'sqlite::memory')
conn = config.gateways[:default].connection
conn.create_table(:users) do
primary_key :id
column :name, String
column :account_type, String
column :account_id, Integer
end
conn.create_table(:sitters) do
primary_key :id
column :name, String
end
conn.create_table(:sitter_profiles) do
primary_key :id
column :sitter_id, Integer
column :about, String
end
config.relation(:users) do
auto_struct true
schema(:users, infer: true) do
associations do
belongs_to :sitter, foreign_key: :account_id
has_one :sitter_profile, through: :sitters
end
end
def sitters
where(account_type: 'Sitter')
end
end
config.relation(:sitters) do
auto_struct true
schema(:sitters, infer: true) do
associations do
has_one :sitter_profile, as: :profile
has_one :user, foreign_key: :account_id, view: :sitters
end
end
end
config.relation(:sitter_profiles) do
auto_struct true
schema(:sitter_profiles, infer: true)
end
rom = ROM.container(config)
users = rom.relations[:users]
sitters = rom.relations[:sitters]
profiles = rom.relations[:sitter_profiles]
sitter = sitters.command(:create).call(name: "Jane")
profile = profiles.command(:create).call(sitter_id: sitter.id, about: 'About Bob')
user = users.command(:create).call(name: 'Bob', account_id: sitter.id, account_type: 'Sitter')
puts sitters.combine(:user).first.inspect
puts users.combine(:sitter).first.inspect
puts users.combine(sitter: :profile).first.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment