Rails/ActiveRecord:如何按与相关模型的关联度排序记录



我有两个模型。

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

我正在尝试找到一种方法来按旅游协会的数量对国家进行排序。

我被引导相信我应该加入与国家/地区的游客表,然后按游客分组,然后再订购将计数最多的组放在顶部。

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

然而,这似乎不太正确。首先,我收到折旧警告。

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)

另外,我认为我没有得到正确的值,因为first之后的所有内容都是零。

获取关联最多的记录的正确方法是什么?

我没有测试,但以下必须工作,

Country.joins(:tourists).group('tourists.id').order('COUNT(tourists.id)')

它将按相关游客数量对国家/地区集合进行排序。

要在顶部获得最大计数,请更改顺序,如下所示,

Country.joins(:tourists).group('tourists.id').order('COUNT(tourists.id) DESC')
您可以使用

left_joins进行此查询

Country.left_joins(:tourists).group('tourists.id').order('COUNT(tourists.id)')

最新更新