【问题标题】:Rails - named scope issue (depends on number of children in a many_to_many relationship)Rails - 命名范围问题(取决于 many_to_many 关系中的子项数量)
【发布时间】:2011-02-08 13:57:09
【问题描述】:

假设我在用户和组之间有一个多对多的关系。用户可以是组的成员,或者他的申请仍处于待处理状态。

class User < ActiveRecord::Base
  has_many :applications
  has_many :groups, :through => :applications
end

class Group < ActiveRecord::Base
  has_many :applications
  has_many :users, :through => :applications
end

class Application < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
  attr_accessible :pending # boolean : is the application still pending or not
end

我想为我的 Group 类添加一个范围,以选择拥有超过 10 个非待定用户的组。

我可以得到这样的成员

Group.joins(:applications).where('applications.pending = ?', false)

但我没有找到足够的资源来创建计算此查询结果数量的范围,并返回此数字大于 10 的组

如果您对此主题有解决方案或资源,这将对我有很大帮助

【问题讨论】:

    标签: sql ruby-on-rails activerecord count named-scope


    【解决方案1】:

    我没有在我自己的控制台中指定您的模型,但是这些方法不会起作用吗?

    Group.joins(:applications).group('groups.id').having('COUNT(*) > 10').where(["applications.pending = ?", false])
    

    基本上,一旦在底层 SQL 中包含 GROUP BY 条件,就可以对聚合结果使用 HAVING。 WHERE 只是将其限制为您正在寻找的那些结果。您可以使用直接 SQL 获得相同的结果:

    Group.find_by_sql(["SELECT * FROM groups INNER JOIN applications ON applications.group_id = groups.id WHERE applications.pending = ? GROUP BY groups.id HAVING COUNT(*) > ?", false, 10])
    

    包含在命名范围中的大型查询。您可能需要考虑将其拆分为多个部分 - 以后可能会省去很多麻烦...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      相关资源
      最近更新 更多