【问题标题】:Rails ActiveRecord combining result of multiple queriesRails ActiveRecord 组合多个查询的结果
【发布时间】:2018-01-31 10:00:08
【问题描述】:

型号:

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 的玩家的玩家信息。提前致谢。

【问题讨论】:

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


    【解决方案1】:

    修复关系定义中的顺序:

    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)
    

    【讨论】:

    • 那行不通。玩家有多个评级,可以上升或下降。我想获得最新的评级并按降序排序。根据你的建议,每个玩家都会有多个评分,而不是最新的评分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多