【发布时间】:2016-12-23 08:53:10
【问题描述】:
我有一个Profile,可以是published。一个profile 属于:user 和has_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_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吗? -
我看到
profiles和users是一样的。用户只有一个字段email。您可以只使用 1 个表users并删除表profiles吗?
标签: ruby-on-rails activerecord ruby-on-rails-5