订购用ActiveRecord和Postgres的结果通过声明的has_many [英] Ordering results with ActiveRecord and Postgres with has_many through statement

查看:155
本文介绍了订购用ActiveRecord和Postgres的结果通过声明的has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这3款车型在这里:

I have these 3 models here:

class User < ActiveRecord::Base
  has_many :parties, foreign_key: 'organizer_id'

  has_many :invitations, foreign_key: 'attendee_id'
end

class Party < ActiveRecord::Base
  belongs_to :organizer, class_name: 'User'

    has_many :invitations
    has_many :attendees, through: :invitations
end

class Invitation < ActiveRecord::Base
  belongs_to :party
  belongs_to :attendee, class_name: 'User'
  belongs_to :inviter, class_name: 'User'
end

我要得到所有与会者为特定政党和那些谁邀请了大多数人对它们进行排序。

I want to get all attendees for a specific party and sort them by those who invited the most people.

我如何做到这一点?

感谢您的帮助。

推荐答案

夫妇可能的解决方案:

party.attendees.joins(:invitations).select('parties.*', 'COUNT(DISTINCT invitations.id) as invitation_count').group('parties.id').order('invitation_count')

优点:可能会奏​​效

Pros: might work

缺点:这是丑陋的,没有解释自己和你将最终获得一个工作非常努力来查询的关系。而避免的。

Cons: This is ugly, does not explain itself and you will end up with an extremely hard to query relation. Rather avoid.

它排序的应用水平:

party.attendees.includes(:invitations).sort_by {|att| att.inivtaions.to_a.size }

优点:这是更清楚自己在做什么。

Pros: It is more clear what you're doing

缺点:返回非querable数组,而不是关系。还需要说明为什么你叫 to_a (避免N + 1问题)。

Cons: Returns non-querable array instead of relation. Still need explanation why you're calling to_a (to avoid N+1 problem).

添加一个额外的列 invitations_count 来参加表格,并添加 counter_cache:真正的 belongs_to的:与会者在你邀请的模型。利润!

Add an extra column invitations_count to attendees table, and add counter_cache: true to the belongs_to :attendee in your Invitation model. Profit!

party.attendees.order(:invitations_count)

优点:尼斯和不言自明的。无需从数据库装载邀请。轻松querable关联。

Pros: Nice and self-explanatory. No need to load invitations from the database. Easily querable association.

缺点:您需要更新所有记录counter_cache你开始使用它之前:

Cons: You need to update all the records' counter_cache before you start using it:

Attendees.includes(:invitations).each { |att| att.invitation_count = att.invitation.to_a.size }

在此,轨道将保持同步列有许多与与会者inivtations相关服务。

After this, rails will take care of holding the column in sync with a number of associated with attendee inivtations.

这篇关于订购用ActiveRecord和Postgres的结果通过声明的has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆