Skip to content

Instantly share code, notes, and snippets.

@flash-gordon
Created April 29, 2016 15:37
Show Gist options
  • Save flash-gordon/19a41183aba20b2fc8f2c5915d6624e2 to your computer and use it in GitHub Desktop.
Save flash-gordon/19a41183aba20b2fc8f2c5915d6624e2 to your computer and use it in GitHub Desktop.
class Users < ROM::Relation[:sql]
schema(:users) do
attribute :id, Types::Serial
attribute :name, Types::String
associate do
many :posts
many :labels, through: :posts
end
end
end
class Posts < ROM::Relation[:sql] do
schema(:posts) do
attribute :id, Types::Serial
attribute :author_id, Types::ForeignKey(:users)
attribute :title, Types::String
attribute :body, Types::String
associate do
many :labels, through: :posts_labels
belongs :author, relation: :users
end
end
end
class PostLabels < ROM::Relation[:sql]
schema(:post_labels) do
attribute :post_id, Types::ForeignKey(:posts)
attribute :label_id, Types::ForeignKey(:labels)
primary_key :post_id, :label_id
associate do
belongs :posts
belongs :labels
end
end
end
class UserRepo < ROM::Repository[:users]
end
user_repo = UserRepo.new(rom_container)
user_repo.aggregate(:posts, :labels) # ╰(✿˙ᗜ˙)੭━☆゚.*・。゚
__END__
#<ROM::Struct[User] id=1 name="Jane" posts=[#<ROM::Struct[Post] id=1 author_id=1 title="Hello From Jane" body="Jane Post">] labels=[#<ROM::Struct[Label] id=1 name="red" author_id=1>, #<ROM::Struct[Label] id=3 name="blue" author_id=1>]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment