Looks like my emails are not getting to the list today. I forward this answer to your inbox directly.
Here are my models:
class User < ActiveRecord::Base
class Picture < ActiveRecord::Base
How do I get a random list of 3 users who have at least one picture
associated with them using ActiveRecord? Sounds fun... I know :-).
A possible (untested) approach that does not rely on the usual SQL idiom for random rows that orders the table. Assumes the set of user IDs is not sparse:
ntrials = 0
max_id = User.maximum("id")
ntrials += 1
random_users = 
[1, rand(max_id), rand(max_id)].sort.each_cons(2) do |a, b|
user = User.find_by_sql(<<-SQL
FROM users u, pictures p
WHERE u.id BETWEEN a AND b
AND u.id = p.user_id
break if user.nil?
# the unless condition takes care of corner cases when
# random limits coincide
random_users << user unless random_users.include?(user)
redo if random_users.size < 3 && ntrials < MAX_TRIALS
That needs extra code for edge cases, but you see the idea.