Rails/ActiveRecord: How do I order records by the most associations with a related model?

Rails/ActiveRecord: How do I order records by the most associations with a related model?

I have two models.

I have two models.

class Tourist < ApplicationRecord
  has_many :visits
  has_many :countries, through: :visits
end

class Country < ApplicationRecord has_many :visits has_many :tourists, through: :visits end

class Visit < ApplicationRecord belongs_to :country belongs_to :tourist end

I am trying to find a way to sort the countries by the number of tourist associations.

I'm led to believe I should join the tourist's table with countries, then group by tourist before ordering to place the group with the largest count at the top.

Country.joins(:tourist).group(:tourist_id).order('COUNT()')

However, this doesn't seem to be quite right. Firstly, I get a depreciation warning.

DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with a non-attribute argument(s): "COUNT()". Non-attribute arguments will be disallowed in Rails 6.0. This method should not be called with user-provided values, such as request parameters or model attributes. Known-safe values can be passed by wrapping them in Arel.sql(). (called from pry at (pry):61)

Also, I don't think I'm getting the correct values because everything after first is nil.

What is the correct way to get the records with the most associations?

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Ruby on Rails vs PHP

Understanding the pros and cons of Ruby on Rails versus PHP is important when deciding how to create your business-critical applications.