【问题标题】:Rails 3 ActiveRecord & Postgres: order by count on associationRails 3 ActiveRecord 和 Postgres:按关联排序
【发布时间】:2013-03-18 14:12:14
【问题描述】:

我有以下 2 个导轨型号:

class Profile < ActiveRecord::Base
  belongs_to :user

  has_many :votes, through: :user

  default_scope includes(:user)

end

class Vote < ActiveRecord::Base
  attr_accessible :by, :for

  belongs_to :by, class_name: "User"
  belongs_to :for, class_name: "User"

  validates :by, :for, presence: true

  validates_uniqueness_of(:by, scope: :for)
end

我正在尝试在个人资料上创建一个“顶级”范围,该范围根据相关用户记录收到的“赞成”票数对个人资料进行排序

投票是由用户为用户创建的。 “by”栏表示投票的用户,“for”栏表示收到投票的用户。我正在尝试获取获得最多选票的用户的个人资料。

这是我目前得到的:

   scope :top,
    select("profile.*, count(votes.id) AS votes_count").
    joins(:votes, :user).
    order("votes_count DESC")

这不适用于以下错误:

ActiveRecord::StatementInvalid: PG::Error: ERROR: column “votes_count”不存在

它也没有考虑“for”列

谁能帮帮我?

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 postgresql activerecord


    【解决方案1】:

    我相信你缺少一个分组。 这是您要执行的查询:

    select profiles.*, count(votes.id) as votes_count 
      from profiles 
      left join votes on votes.for_id = profiles.user_id 
      group by profiles.id 
      order by votes_count desc;
    

    所以,让我们把它变成一个 ActiveRecord 范围:

    scope :top, joins('left join votes on votes.for_id = profiles.user_id').
      select('profiles.*, count(votes.id) as votes_count').
      group('profiles.id').
      order('votes_count desc')
    

    【讨论】:

    • 非常感谢,这很有帮助。我没有将个人资料更改为个人资料,这是我的错误。
    • 这类作品:scope :top, joins('join votes on votes.for = profiles.user_id')。 select('profiles.*, count(votes.id) as votes_count')。组('profiles.id')。 order('votes_count desc') 但我似乎只得到 1 个配置文件,即使我想要一个按票数排序的整个列表。我该如何解决这个问题?
    • 您是否只有一个配置文件为其用户投票?如所写,查询将排除任何没有投票的人。如果您想在不包含任何配置文件的情况下包含配置文件,请将 join votes 切换为 left join votes。 (我已经修改了答案以反映这一点)
    • 谢谢,我犯了一个小错误,只导致我得到 1 个结果。你最初的答案是正确的。再次感谢。
    • 这行得通,只是它删除了关联记录数为 0 的记录。任何解决方法,包括关联记录数为 0 的记录?
    【解决方案2】:

    ActiveRecord方式

    Profile.joins(:votes).group("profiles.id").order("count(profiles.id) DESC")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多