Created
June 4, 2015 12:28
-
-
Save stravid/57986ebadfdec7fa3bc8 to your computer and use it in GitHub Desktop.
This file contains 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 'rubygems' | |
require 'bundler/setup' | |
require 'rom' | |
require 'rom-sql' | |
ROM.setup(:sql, 'postgres://localhost/datsu_development') | |
class Players < ROM::Relation[:sql] | |
register_as :players | |
dataset :players | |
end | |
class Throws < ROM::Relation[:sql] | |
register_as :throws | |
dataset :throws | |
def for_users(users) | |
where(player_id: users.map { |user| user[:id] }).order(:order).limit(2) | |
end | |
end | |
class PlayersMapper < ROM::Mapper | |
relation :players | |
register_as :with_throws | |
reject_keys true | |
attribute :id | |
attribute :name | |
combine :throws, on: { id: :player_id } | |
end | |
ROM.finalize | |
rom = ROM.env | |
puts rom.relation(:players).combine(rom.relation(:throws).for_users).as(:with_throws).to_a | |
# Returns an empty hash as throw | |
{:id=>1, :name=>"David", :throws=>[{}]} | |
{:id=>2, :name=>"Thomas", :throws=>[{}]} | |
# Removing `reject_keys true` produces the correct output | |
{:id=>1, :created_at=>2015-05-09 12:33:50 +0200, :updated_at=>2015-05-09 12:33:50 +0200, :name=>"David", :throws=>[{:id=>57, :match_id=>5, :player_id=>1, :is_bust=>false, :darts=>"[\"5\",\"20\",\"T20\"]", :order=>0, :created_at=>2015-05-09 12:33:50 +0200, :updated_at=>2015-05-09 12:46:10 +0200, :score=>85, :score_before_throw=>301, :score_after_throw=>216}]} | |
{:id=>2, :created_at=>2015-05-09 12:33:50 +0200, :updated_at=>2015-05-09 12:33:50 +0200, :name=>"Thomas", :throws=>[{:id=>58, :match_id=>5, :player_id=>2, :is_bust=>false, :darts=>"[\"2\",\"5\",\"1\"]", :order=>1, :created_at=>2015-05-09 12:33:50 +0200, :updated_at=>2015-05-09 12:46:10 +0200, :score=>8, :score_before_throw=>301, :score_after_throw=>293}]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment