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
You could also use a INTERSECT based approach:
def self.find_random_by_labels(labels)
ds1, *dsr = labels.map{|l|
filter(:id=>DB[:labels_signatures].join(:labels,
:id=>:label_id).select(:signature_id).filter(:label__name=>l)}
dsr.inject(ds1){|ds, ds2| ds.intersect(ds2)}.order{random{}}.first
end
On PostgreSQL the first way is significantly faster, and since it is
also simpler, that's the approach I'd use.
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.