Group_by in Rails

Sort group IDs in descending order of members

group_id user_id
1 1
1 2
1 3
2 2
3 1
3 3

groupsHash = groups.group(:group_id).order('count(user_id) desc').count(:user_id)
#=> {1=>3, 3=>2, 2=>1}

Get an array of group ids with 2 or more people from here


ids = groupsHash.filter_map{ |group| groupsHash[0].to_i if groupsHash[1] >= 2}

#=> [1, 3]

Recommended Posts

Group_by in Rails
Adding columns in Rails
Disable turbolinks in Rails
^, $ in Rails regular expression
Use images in Rails
Understand migration in rails
Split routes.rb in Rails6
Implement markdown in Rails
Get UserAgent in [Rails] controller
Implement application function in Rails
Declarative transaction in Rails #ginzarb
Japaneseize using i18n with Rails
Implement LTI authentication in Rails
Gem often used in Rails
View monthly calendar in Rails
Use multiple checkboxes in Rails6!
Rails: Capture regular expressions in emails!
[Rails] Session timeout setting in devise
Add a search function in Rails.
Enable jQuery and Bootstrap in Rails 6 (Rails 6)
[rails] Login screen implementation in devise
[Rails] Unexpected validation error in devise
About the symbol <%%> in Rails erb
[Rails] Use cookies in API mode
Implement simple login function in Rails
Create a new app in Rails
Ruby on Rails Japanese-English support i18n
[Solution] Webpacker :: Manifest :: MissingEntryError in Rails
Implement a contact form in Rails
Remove "assets" and "turbolinks" in "Rails6".
CRUD features and MVC in Rails
How to introduce jQuery in Rails 6
First pagination feature added in rails
Data is not registered in Rails.
[Rails 6] Customize Bootstrap in Rails + Bootstrap 5.0.0-alpha environment
Implement CSV download function in Rails
Ruby methods often used in Rails
How to install Swiper in Rails
[Rails g.error]
Rails basics
Rails Review 1
How to implement search functionality in Rails
Definitions other than 7 basic actions in Rails
[Rails] Function restrictions in devise (login / logout)
Rails API
Rails migration
[Rails] first_or_initialize
rails tutorial
How to insert a video in Rails
The identity of params [: id] in rails
[rails] List of actions defined in Controller
Rails foundation
Rails refactoring story learned in the field
Rails memorandum
Ruby on Rails in Visual Studio Codespaces
JavaScript (vanilla) does not respond in Rails.
rails tutorial
rails tutorial
How to use MySQL in Rails tutorial
rails tutorial
Specify home view in rails app [root]