型号:
player
belongs_to :current_club
belongs_to :parent_club
has_many :ratings
rating
belongs_to :player
基本架构:
create_table "clubs", force: :cascade do |t|
t.integer "league_id"
t.string "club_name"
end
create_table "players", force: :cascade do |t|
t.integer "player_id"
t.string "player_name"
t.integer "current_club_id"
t.integer "parent_club_id"
end
create_table "ratings", force: :cascade do |t|
t.integer "player_id"
t.integer "rating"
t.date "date"
end
我想获得每个未在特定current_club工作的玩家的最新评分,并按最新评级的降序排列玩家。
要获取所有玩家的最新评分信息并按降序排列,以下作品:
@ratings = Rating.select([:player_id, :rating, :date, 'MAX(date)']).order('rating desc').group(:player_id)
为了获取所有不在特定current_club的玩家的信息,以下作品:
@players = Player.paginate(page: params[:page], per_page: 50).includes(:current_club).where.not(current_club_id: 101121)
我无法弄清楚如何将两者结合起来,以便按降序获得所有玩家的最新评分,以及所有不在current_club 101121的玩家的玩家信息。感谢提前。
答案 0 :(得分:0)
修正关系定义中的顺序:
player
belongs_to :current_club
belongs_to :parent_club
has_many :ratings, -> { order(rating: :desc) }
现在您只需致电:
@players = Player.paginate(page: params[:page], per_page: 50).includes(:current_club, :ratings).where.not(current_club_id: 101121)