-
-
Save ganeshran/d02cf5b3a0e5cd81978d to your computer and use it in GitHub Desktop.
Left outer join
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
⇒ 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