0

일부 기본 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 

groups 및 friends를 사용하면 returning_members 메소드를 범위로 다시 쓸 수 있습니까?

필자는 레일즈 2.3을 사용하고 있지만 새로운 버전을 사용하는 솔루션도 허용 할 것입니다.

답변

1

이 범위를 Season에 넣으려면 반복 사용자가있는 Seasons를 찾고 있다는 것을 의미하기 때문에 확실하지 않습니다. 하지만 반복되는 계절이있는 사용자를 원한다고 가정합니다. 그 가정으로, 당신의 범위는 다음과 같습니다

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 

가 : 3.1.3 및 sqlite3를

+0

아 레일, 난을 참조하십시오. 기꺼이 도와 드릴 수 있습니다. 나는 분명히 조인()으로 코드에서 SQL을 얻는 것에 동의하지만 예제에서는 다른 키가 꽤 종속적이어서 일관성을 위해 거기에 남겨 둘 것이라고 생각했다. :-) -md – miked