基于关联记录数的命名范围

时间:2012-02-03 19:07:31

标签: ruby-on-rails scope group-by has-many-through record-count

我正在做一些基本的sql逻辑,我想使用命名范围。我试图找出一个赛季有多少成员参加了另一个赛季(即他们回归成员)。

class Season
  has_many :season_members
  has_many :users, :through => :season_members

  def returning_members
    users.select { |u| u.season_members.count > 1 }
  end
end

class SeasonMember
  belongs_to :season
  belongs_to :user
end

class User
  has_many :season_members
end

是否可以使用:group和friends将returns_members方法重写为范围?

我碰巧使用的是Rails 2.3,但我也会接受依赖更新版本的解决方案。

1 个答案:

答案 0 :(得分:1)

不确定你是否真的想把这个范围放在Season上,因为这意味着你正在寻找有重复用户的季节。但是,我认为你想要有重复季节的用户。根据这个假设,您的范围将是:

class User < ActiveRecord::Base
 scope :repeat_members, 
    :select=>"users.*, count(season_members.season_id) as season_counter",
    :joins=>"JOIN season_members ON season_members.user_id = users.id",
    :group=>"users.id",
    :having=>"season_counter > 1"
end

会导致以下查询:

 SELECT users.*, count(season_members.season_id) as season_counter FROM "users" JOIN season_members ON season_members.user_id = users.id GROUP BY users.id HAVING season_counter > 1

确认:Rails 3.1.3和SQLite3