Created
November 23, 2016 07:53
-
-
Save jmcervera/100a76854eef754d65bb284599e11448 to your computer and use it in GitHub Desktop.
Nested associations with rom-rb
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
# Hi, this is the setup of my problem. | |
# The thing is that I'm working in a legacy database where primary keys are not autoincrement ids, | |
# They're strings and are named <<entity>>_id. | |
# Also some foreign keys are named diferrently like the one for zones in journeys relation, that is named | |
# start_zone_id | |
# | |
# The queries that I pretend to implement are explained in comments in the repository class. | |
class Interval < ROM::Relation[sql] | |
schema(:interval) do | |
attribute :interval_id, Types::String.meta(prmary_key: true) | |
attribute :journey_id, Types::ForeignKey(:journeys, Types::String) | |
attribute :state, Types::String | |
attribute :created_at, Types::DateTime | |
associations do | |
belongs_to :journey | |
end | |
end | |
end | |
class Journey < ROM::Relation[sql] | |
schema(:interval) do | |
attribute :journey_id, Types::String.meta(prmary_key: true) | |
attribute :description, Types::String | |
attribute :start_zone_id, Types::ForeignKey(:zones, Types::String) | |
associations do | |
belongs_to :zone | |
has_many :intervals | |
end | |
end | |
end | |
class Zone < ROM::Relation[sql] | |
schema(:interval) do | |
attribute :zone_id, Types::String.meta(prmary_key: true) | |
attribute :name, Types::String | |
associations do | |
has_many :journeys | |
end | |
end | |
end | |
class IntervalRepo < ROM::Repository[:intervals] | |
def first_query(initial_date, final_date) | |
# I pretend to have a query that retrieves all the intervals created between initial and final dates. | |
# And retrieve at the same time the journeys and the zones associated, nested in the same resulset. | |
end | |
def second_query(initial_date, final_date) | |
# The same as the first query, with the difference that I would like to retrieve the associated journeys and zones | |
# only for intervals in some state. | |
# All the intervals, but only with associated data the ones in some stae | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment