[RUBY] 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
Model association in Rails
Adding columns in Rails
Disable turbolinks in Rails
CSRF measures in Rails
^, $ in Rails regular expression
Use images in Rails
Understand migration in rails
Split routes.rb in Rails6
Implement markdown in Rails
Implement application function in Rails
Declarative transaction in Rails #ginzarb
Japaneseize using i18n with Rails
Implement LTI authentication in Rails
Error in rails db: migrate
Display Flash messages in Rails
View monthly calendar in Rails
Implement import process in Rails
Use multiple checkboxes in Rails6!
Rewrite Routes in Rails Engine
Rails: Capture regular expressions in emails!
[Rails] Keyword search in multiple tables
[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] How to write in Japanese
[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
How to change app name in rails
[Rails] first_or_initialize
rails tutorial
How to insert a video in Rails
About Rails 6
The identity of params [: id] in rails
[rails] List of actions defined in Controller
Rails refactoring story learned in the field
Rails memorandum