On Thursday, August 2, 2012 10:14:54 PM UTC-7, Iain Barnett wrote:
>
> Hello,
>
> Taking the example from the docs[1] of Artist and Album models with a
> many_to_many association defined, what is the "best" (idiomatic,
> fastest...) way to do a join that has several items on each side and get
> back model instances?
>
> For example, if I have one instance of the Artist class, I can get all the
> associated albums:
>
> kinks = Artist[name: "kinks"]
> kinks.albums # or `albums_dataset`
>
> But what if I have more than one artist? Right now, I end up doing
> something like this:
>
> Album.join(:albums_artists, :album_id => :id).join(
> Artist.filter(:name => ["kinks", "animals"]), :id => :artist_id).all
>
> or:
>
> Artist.filter(:name => ["kinks", "animals"]).inject([]){|mem,obj| mem
> + obj.albums }
>
> I'd like to be able to write something like:
>
> Artist.filter(:name => ["kinks", "animals"]).albums
>
> and get back an array, or (even better) a dataset, of all the albums made
> by those 2 artists as model instances. Is this possible?
>
Well, with the dataset_associations plugin, that last example will work.
You could also use the filter by associations support:
Album.where(:artists=>Artist.filter(:name => ["kinks", "animals"]))
I think in both cases, it uses a subselect instead of a join. If you
really must have a join, you can use eager_graph:
Album.eager_graph(:artists).where(:artists__name => ["kinks",
"animals"]).all
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/sequel-talk/-/66kcExof42AJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sequel-talk?hl=en.