On Thursday, September 13, 2018 at 2:53:23 AM UTC-7, Janko Marohnić wrote:
>
> Hi Jeremy,
>
> Is there a way to fetch the association dataset from the model/dataset
> level, which can then be used for making subqueries? To illustrate, let's
> assume the following association declarations:
>
> class Album < Sequel::Model
> end
>
> class Artist < Sequel::Model
> one_to_many :released_albums, class: Album, conditions: { released:
> true }
> end
>
> And let's say that I would like to fetch all artists that have at least
> one released album. Currently I would do it like this:
>
> released_album_count = Album
> .where{albums[:artist_id] =~ artists[:id]}
> .where(released: true)
> .select{count.function}
>
> Artist.where(released_album_count > 0).to_a
>
> However, I feel like here I'm repeating many things (album class, foreign
> key matching, released condition) that are already declared in the
> :released_albums association. Is there any way that I can use the
> :released_albums association to create such a dataset? So that I can do
> just something like:
>
> # here I'm using an imaginary "association_dataset" method
> released_album_count =
> Artist.association_dataset(:released_albums).select{count.function}
>
> Artist.where(released_album_count > 0).to_a
>
I'm guessing this may work in terms of returning an associated dataset:
Artist.association_reflection(:release_albums).send(:eager_loading_dataset)
As you can guess, eager_loading_dataset is a private method.
For what you are doing, I would use a IN subquery, since you don't care
about how many there are, just that at least one matches:
Artist.where(:id=>Album.where(:released).select(:artist_id))
Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.