Skip to content

Instantly share code, notes, and snippets.

@blelump
Last active March 17, 2018 10:58
Show Gist options
  • Save blelump/2f181356f404b70932a015bf2e7cb146 to your computer and use it in GitHub Desktop.
Save blelump/2f181356f404b70932a015bf2e7cb146 to your computer and use it in GitHub Desktop.
ROM Mapper issue
require 'bundler'
require 'dry-types'
Bundler.require
module Types
include Dry::Types.module
end
rom = ROM.container(:sql, 'sqlite::memory') do |conf|
conf.gateways[:default].use_logger(Logger.new($stdout))
conf.default.create_table(:users) do
primary_key :id
column :login, String, null: false
end
conf.default.create_table(:employees) do
primary_key :id
column :name, String, null: false
end
conf.default.create_table(:customers) do
primary_key :id
column :address, String, null: false
end
conf.default.create_table(:employees_users) do
foreign_key :verifable_id, :employees
foreign_key :user_id, :users
end
conf.default.create_table(:customers_users) do
foreign_key :verifable_id, :customers
foreign_key :user_id, :users
end
conf.relation(:users) do
schema(:users, infer: true) do
associations do
has_one :employees_user
has_one :customers_user
has_one :employee, through: :employees_users
has_one :customer, through: :customers_users
end
end
end
conf.relation(:employees) do
schema(:employees, infer: true) do
associations do
has_one :employees_user
# belongs_to :c
end
end
end
conf.relation(:customers) do
schema(:customers, infer: true) do
associations do
has_one :customers_user
# belongs_to :a
# belongs_to :b
end
end
end
conf.relation(:customers_users) do
schema(:customers_users, infer: true) do
associations do
belongs_to :user
belongs_to :customer
end
end
end
conf.relation(:employees_users) do
schema(:employees_users, infer: true) do
associations do
belongs_to :user
belongs_to :employee
end
end
end
end
module E
class User < ROM::Struct
attribute :login, Types::String
end
end
class UserRepo < ROM::Repository[:users]
struct_namespace E
def by_id(id)
users
.combine(:customer)
.combine(:employee)
.by_pk(id)
.one
end
end
employee = rom.relations[:employees].changeset(:create, name: 'Jane').commit
user = rom.relations[:users]
.changeset(:create, login: '[email protected]')
.commit
rom.relations[:employees_users]
.changeset(:create, user_id: user[:id], verifable_id: employee[:id]).commit
repo = UserRepo.new(rom)
user = repo.by_id(1)
p user
#<E::User login="[email protected]" id=1 login="[email protected]" customer=nil employee=#<E::Employee id=1 name="Jane" user_id=1>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment