【问题标题】:How do I sort on an association of a specific user?如何对特定用户的关联进行排序?
【发布时间】:2016-12-23 08:53:10
【问题描述】:

我有一个Profile,可以是published。一个profile 属于:userhas_many :ratings

User has_one :profilehas_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_id,user_id)。这意味着关系 User-Profile 是 n-n。但是您之前设置的关系 profile-user 是 1-1。
  • User-to-Profile 是 1-1,Rating-to-Profile 是 n-n。你是如何让用户配置文件成为 n-n 的?唯一可能是真的,如果我设置了has_many ratings_users through: :ratings,不是吗?
  • User-Rating 1-n, Profile-Rating 1-n => User-Profile n-n
  • 啊有趣。那么你认为的解决方案是什么? User-Profile n-n 不是 thru Rating 吗?
  • 我看到profilesusers 是一样的。用户只有一个字段email。您可以只使用 1 个表 users 并删除表 profiles 吗?

标签: ruby-on-rails activerecord ruby-on-rails-5


【解决方案1】:

使用连接:

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

【讨论】:

  • 如何找到每个关联用户的评分? coach 是我原始查询中的用户。请参阅更新后的问题,以更清楚地了解我在寻找什么。
  • 兄弟....哇...完美。这正是我一直在寻找的。奇迹般有效。如此简单和干净。不敢相信我从来没有想过where(ratings:...)
猜你喜欢
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 2021-03-28
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
相关资源
最近更新 更多