【问题标题】:Order list of records by other created_at record column按其他 created_at 记录列排序记录列表
【发布时间】:2016-05-24 05:54:03
【问题描述】:

在我的桌子上: 用户可以对战斗记录进行投票 战斗记录有很多投票记录(有user_id的用户投票)

我想通过每场战斗的投票记录的 created_at 列对用户投票的战斗进行排序。

英文 - 我想获取用户在投票时投票的战斗列表。

我当前的代码 - 问题是这段代码返回一个数组,我想要它的顺序:

scope :picked, -> (user_id) { where("battles.id IN (SELECT DISTINCT(battle_id) FROM votes WHERE user_id = ?)", user_id)
                                    .sort_by { |b| b.votes.find_by(user_id: user_id ).created_at }.reverse }

【问题讨论】:

    标签: sql ruby-on-rails postgresql ruby-on-rails-4


    【解决方案1】:

    在指定 has_many 关联时,您必须传递一个阻止选项。
    假设您有以下模型:

    Vote < ActiveRecord::Base
     belongs_to :user
     belongs_to :battle
    end  
    

    还有:

    Battle < ActiveRecord::Base
    
    end
    

    用户模型应该是这样的:

    User < ActiveRecord::Base
      has_many :votes, -> { order(created_at: :desc) } # Ordering goes here
      has_many :battles, through: :votes
    end    
    

    那你直接查询战斗:
    User.first.battles # Scoped by votes.created_at

    【讨论】:

    • 我不想返回用户的战斗,我想返回用户投票的战斗......
    • @gal 我定义的关联将只返回被投票的战斗。您能否显示用户/投票/战斗模型代码,以便我可以看到您指的是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2021-08-28
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多