Skip to content

Instantly share code, notes, and snippets.

@cutalion
Last active September 14, 2017 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cutalion/86008fe3273ae5badcd93a18cbbaf6e1 to your computer and use it in GitHub Desktop.
Save cutalion/86008fe3273ae5badcd93a18cbbaf6e1 to your computer and use it in GitHub Desktop.
ROM issue with polymorphic association and aggregation
source "https://rubygems.org"
gem 'sqlite3'
gem 'dry-logic', github: 'dry-rb/dry-logic', branch: 'master'
gem 'dry-types', github: 'dry-rb/dry-types', branch: 'master'
gem 'rom', github: 'rom-rb/rom', branch: 'master'
gem 'rom-sql', github: 'rom-rb/rom-sql', branch: 'master'
gem 'pry'
require 'rom'
require 'rom-repository'
require 'rom-sql'
require 'pry'
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
end
conn.create_table(:sitter_profiles) do
primary_key :id
column :sitter_id, Integer
column :about, String
end
config.relation(:users) do
schema(:users, infer: true) do
associations do
belongs_to :sitter, foreign_key: :account_id, view: :for_users
has_one :sitter_profile, through: :sitters
end
end
def sitters
where(account_type: 'Sitter')
end
end
config.relation(:sitters) do
schema(:sitters, infer: true) do
associations do
has_one :sitter_profile, as: :profile
has_one :user, foreign_key: :account_id, view: :sitters
end
end
def for_users
join(:users, account_id: :id)
end
end
config.relation(:sitter_profiles) do
schema(:sitter_profiles, infer: true)
end
class Users < ROM::Repository[:users]
commands :create
end
class Sitters < ROM::Repository[:sitters]
commands :create
end
class SitterProfiles < ROM::Repository[:sitter_profiles]
commands :create
end
rom = ROM.container(config)
user_repo = Users.new(rom)
sitter_repo = Sitters.new(rom)
profile_repo = SitterProfiles.new(rom)
sitter = sitter_repo.create({})
profile = profile_repo.create(sitter_id: sitter.id, about: 'About Bob')
user_repo.create(name: 'Bob', account_id: sitter.id, account_type: 'Sitter')
puts sitter_repo.aggregate(:user).first
puts sitter_repo.aggregate(:user).first.user.name
puts user_repo.aggregate(:sitter).to_a #=> rom-fb98641ad662/core/lib/rom/relation/curried.rb:112:in `method_missing': undefined method `preload_assoc' for #<ROM::Relation::Curried:0x000000027b2260> (NoMethodError)
# question: how to get user with sitter and sitter_profile?
puts user_repo.aggregate(sitter: :profile).to_a.first.sitter.profile.about
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment