0

I'd like an ActiveRecord query that lets me return all the users that have zero email_sessions. Here're my models:

class User
    has_many :email_sessions
end

class EmailSession
    belongs_to :user
end

It would be pretty straight-forward to do this after the AR query, like so:

User.all.reject {|u| u.email_sessions.count > 0}

But it gets to be pretty computationally-expensive as it steps through every user to check the count. I also want to use arel to chain together different where statements after this.

Any ActiveRecord sooper geniuses want to take a crack at this? :-)

Aaron Vegh
  • 5,217
  • 7
  • 48
  • 75

2 Answers2

1

This is how I would do it, but unfortunately in an older version of Rails. Perhaps there are better ways of doing it in newer versions.

User.find(:all,
  :include => :email_sessions,
  :conditions => 'email_sessions.id IS NULL'
)

EDIT: Using ARel:

User.includes(:email_sessions).where('email_sessions.id IS NULL')
244an
  • 1,579
  • 11
  • 15
0
[64] pry(main)> User.all.reject {|u| u.trial_end_date == nil or u.email_sessions.count > 0}.count
=> 138
[65] pry(main)> User.where("users.id NOT IN(?) AND users.trial_end_date IS NOT NULL", EmailSession.group(:user_id).select(:user_id).map { |es| es.user_id }).count
=> 138
Victor S
  • 5,098
  • 5
  • 44
  • 62
  • 2
    Victor is cheating a bit because I work with him, and he tested on the actual data. This solution works perfectly. – Aaron Vegh Nov 20 '12 at 20:59
  • The question is why did you have to post on SO when Victor is there? :) – Mark Thomas Nov 20 '12 at 21:08
  • Also, doesn't even match the question. At the very least edit the question to match this, so someone in the future can make sense of it. – rking Nov 20 '12 at 21:16
  • 1
    While good information, this would be really confusing to future readers. Please change to be a general answer fitting the question. – joofsh Nov 20 '12 at 21:18