On Feb 6, 8:34 am, Piotr Szotkowski <[email protected]> wrote:
> As usual – thanks a lot for the prompt reply!
>
> Jeremy Evans:
>
>
>
> > On Feb 5, 3:07 pm, Piotr Szotkowski <[email protected]> wrote:
> >> module Signore class Signature < Sequel::Model
>
> >>   many_to_many :labels
>
> >>   def self.find_random_by_labels labels
> >>     sigs = labels.empty? ? all : labels.map { |label| Label[:name => 
> >> label].signatures rescue [] }.inject(:&)
> >>     sigs.sort_by { rand }.first
> >>   end
>
> >> end end
> > This makes some assumptions about your schema,
> > but it or something similar should work:
> >   def self.find_random_by_labels(labels)
> >     order{random{}}.first(labels.map{|l| [:id, 
> > DB[:labels_signatures].join(:labels, 
> > :id=>:label_id).select(:signature_id).filter(:label__name=>l)]})
> >   end
>
> Hm, I don’t think I get this example (even after reading the
> Sequel::Dataset#first docs…). You map the labels into two-elements
> Arrays with :id as the first element and a query that fetches the
> relevant signature_ids for a given label – but where does it do the
> intersection of the signatures?

The array of two element arrays is treated like a hash except that you
can have multiple identical keys (necessary in this case).  It would
probably would help to see the SQL produced for labels = ['a', 'b']:

SELECT * FROM signatures
WHERE ((id IN (SELECT signature_id FROM labels_signatures INNER JOIN
labels ON (labels.id = labels_signatures.label_id) WHERE (label.name =
'a'))) AND
       (id IN (SELECT signature_id FROM labels_signatures INNER JOIN
labels ON (labels.id = labels_signatures.label_id) WHERE (label.name =
'b'))))
ORDER BY random() LIMIT 1

If you still have questions, please let me know.

Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
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.

Reply via email to