Repositories: filter on an association

Hi,

I’m trying to figure out how to use associations in my repositories. Let’s reuse the example from the docs: http://hanamirb.org/guides/1.0/models/associations/

How do I look for the list of authors who used “Missing You” (and there are a few according to goodreads.com) as title of one of their books? In Sequel I’d write something along the lines of:

DB[:authors].books.where(title: 'Missing You')

But in Hanami I have no clue how to do it. Since under the hood Hanami uses ROM which under the hood uses Sequel, I tried something like:

aggregate(:books).where(books__title: 'Missing You')

but it fails because somehow the generated SQL query does not join the books table (I suspect the aggregate is not applied immediately). So as a workaround I do something ugly like this:

aggregate(:books).to_a
                 .select { |c| !c.books.empty? &&
                               c.books[0].title == 'Missing You' }

I’d like to know how to do it properly though.

Hello! You need to use #join here. Try this code:

def books_with_title(title)
  books # => books relation
  aggregate(:books).josin(:books).where(books[:title].qualified => 'Missing You')
end

And more information you can find here: https://stackoverflow.com/questions/43080678/join-query-in-hanami-model/43156257#43156257

Thanks, it works as expected!

I guess that the choice of using ROM is architecturally sound, but that makes it yet another library to learn, and its documentation seems lacking to me. I might have replaced it by Sequel by now if that didn’t imply losing the database commands, including migrations.

We offer full association support on 1.1, @malin-as.

class AuthorRepository < Hanami::Repository
  associations do
    has_many :books
  end

  def authors_who_wrote_books_titled(book_title)
    aggregate(:books).where(books[:title].qualified => book_title).map_to(Author).to_a
  end
end

That’s good news, though my main concern is not really the features themselves but their documentation. So far, I’ve had a really great experience with the docs (unlike many other Ruby projects). But I can’t get a clear picture of what ROM is, or does, and how it integrates Sequel, and how it integrates into Hanami too. It feels like I’m trying to write queries with Sequel but with two layers (ROM, Hanami-model) “interfering”, hence quite confusing.

Yeah. rom-sql (which underpins hanami-model right now) could certainly use more detailed docs. It works on top of Sequel, so most of it is available to it

Why rom has different methods? 'Cause it supports more than just SQL (git repos, flat files seem to work just fine with it) using the same abstractions. The docs at rom-rb.org are what they have for now (besides RDocs).