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

三世轮回 提交于 2019-12-12 04:14:01

问题


I have a Profile that can be published. A profile belongs_to :user and has_many :ratings.

A User has_one :profile, and has_many :ratings.

A Rating belongs_to :profile && belongs_to :user.

These are the schemas for the above models:

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
#

What I want to do is to find all the profiles, ranked by 1 rating attribute....e.g. all published profiles ranked by passing (highest to lowest).

I tried something like this:

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

But that doesn't always give me the profiles in the order I expect.

So how do I do this query that allows me to get these profiles ranked by all of those ratings accordingly?

Edit 1

Please Note The key thing here is that I need to find the ratings on a profile left by a specific user.

In my query above, coach = User.find(7).

So each User leaves a bunch of ratings on many profiles.

What I want to do is filter all the profiles, that have a specific rating (say speed) and order those profiles, by the speed rating from highest to lowest (but this is user specific).


回答1:


Use a join:

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


来源:https://stackoverflow.com/questions/41298136/how-do-i-sort-on-an-association-of-a-specific-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!