如何对特定用户的关联进行排序?

How do I sort on an association of a specific user?

我有一个 Profile 可以是 published。 A profile belongs_to :userhas_many :ratings.

一个User has_one :profile,和has_many :ratings

一个Rating belongs_to :profile && belongs_to :user.

这些是上述模型的架构:

Profile.rb:

# == Schema Information
#
# Table name: profiles
#
#  id                      :integer          not null, primary key
#  first_name              :string
#  last_name               :string
#  created_at              :datetime         not null
#  updated_at              :datetime         not null
#  user_id                 :integer

User.rb:

# == Schema Information
#
# Table name: users
#
#  id                     :integer          not null, primary key
#  email                  :string           default(""), not null
#  created_at             :datetime         not null
#  updated_at             :datetime         not null
#  first_name             :string
#  last_name              :string

Rating.rb

# == Schema Information
#
# Table name: ratings
#
#  id         :integer          not null, primary key
#  speed      :integer          default(0)
#  passing    :integer          default(0)
#  tackling   :integer          default(0)
#  dribbling  :integer          default(0)
#  profile_id :integer
#  user_id    :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

我想要做的是找到所有配置文件,按 1 rating 属性排名....例如所有已发布的个人资料排名 passing(从高到低)。

我试过这样的事情:

Profile.published.where(id: coach.ratings.order(passing: :desc).pluck(:profile_id))

但这并不总是按照我期望的顺序给我配置文件。

那么,我该如何执行此查询,使我能够根据所有这些评级相应地对这些配置文件进行排名?

编辑 1

请注意 这里的关键是我需要找到特定用户留下的个人资料的评分。

在我上面的查询中,coach = User.find(7)

所以每个 User 在许多 profiles 上留下一堆 ratings

我想做的是过滤所有 profiles,具有特定等级(比如 speed)并按速度等级从最高到最低排序这些配置文件(但这是用户特定)。

使用连接:

Profile.published
  .joins(:ratings)
  .where(ratings: { user_id: coach.id } )
  .order('ratings.passing')