Skip to content

Instantly share code, notes, and snippets.

@ganeshran
Created August 26, 2014 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ganeshran/d02cf5b3a0e5cd81978d to your computer and use it in GitHub Desktop.
Save ganeshran/d02cf5b3a0e5cd81978d to your computer and use it in GitHub Desktop.
Left outer join
class Cuuser < ActiveRecord::Base
has_and_belongs_to_many :groups
has_many :messages
has_many :comments
has_many :likes
scope :activeusersleft, -> { joins("LEFT OUTER JOIN comments ON comments.cuuser_id = cuusers.id LEFT OUTER JOIN likes ON likes.cuuser_id = cuusers.id LEFT OUTER JOIN messages on messages.cuuser_id = cuusers.id").
select('cuusers.id, count(messages.id) as message_count, count(likes.id) as likes_count, count(comments.id) as comments_count').
group('cuusers.id').
order('count(comments.id) + count(likes.id) + count(messages.id) desc')}
end
⇒ rails console
Loading development environment (Rails 4.0.3)
2.0.0p353 :001 > Cuuser.activeusersleft
Cuuser Load (1.5ms) SELECT cuusers.id, count(messages.id) as message_count, count(likes.id) as likes_count, count(comments.id) as comments_count FROM
"cuusers" LEFT OUTER JOIN comments ON comments.cuuser_id = cuusers.id LEFT OUTER JOIN likes ON likes.cuuser_id = cuusers.id LEFT OUTER JOIN
messages on messages.cuuser_id = cuusers.id GROUP BY cuusers.id ORDER BY count(comments.id) + count(likes.id) + count(messages.id) desc
=> #<ActiveRecord::Relation [#<Cuuser id: 1>]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment