2012-01-12 2 views
4

레일에서 mysql 함수 GROUP_CONCAT을 수행하려고합니다. 활성 레코드 계산 방법을 사용하고 있습니다. like this self.calculate (: group_concat, : id)self.calculate 사용시 정의되지 않은 오류가 발생했습니다.

이것이 올바른지 알고 싶지 않습니다.

레일스에서 ​​group_concat을 수행하는 방법에 대한 아이디어가 있습니까? 과 함께 activerecord 메소드를 찾습니다.

+0

원하는 원시 SQL을 언제든지 실행할 수 있습니다. –

+0

예 sergio,하지만 그 경우에는 많은 코드를 변경해야합니다. 활성 레코드 찾기 메서드를 사용하고 있기 때문에 이미 쿼리를 생성하고 있습니다. 그래서 원시 SQL 쿼리를 사용하지 않고 group_concat을 통합하는 방법이 있습니까? 그리고 귀하의 회신에 대한 thnx btw .. – Hitesh

+0

이 문제에 대한 실제 SQL 쿼리가 있다면 .. 그것도 여기에 게시하십시오. –

답변

0

위의 @Camway 노트와 마찬가지로 JOINing, SELECTing 및 GROUPing에 적합한 레일스 방법론을 사용하면 쉽게 수행 할 수 있습니다. 예를 들어 사용자와 지역이 있고 사용자가 0 대 다수 지역을 가질 수 있고 지역이 0 대 다수 사용자를 가질 수 있다고 가정 해 봅시다.

class Region < ActiveRecord::Base 
    # attributes: id (integer), code (string) 
    has_and_belongs_to_many :users 
end 

가 여기 내 사용자 모델의 :

가 여기 내 지역 모델의 물론,

class User < ActiveRecord::Base 
    # attributes: id (integer), email (string) 
    has_and_belongs_to_many :regions 
end 

이 또한 regions_users는 REGION_ID과 user_id를 정수로 테이블을 조인 전지. 그래서

class User < ActiveRecord::Base 
    # attributes: id (integer), email (string) 
    has_and_belongs_to_many :regions 

    class << self 
    def regions_listing 
     joins(:regions) 
     .select("DISTINCT users.email, GROUP_CONCAT(DISTINCT regions.region_code ORDER BY regions.region_code) AS regions_list") 
     .group("users.email") 
     .order("users.email") 
    end 
    end 
end 

:

각 사용자가, 난 그냥 사용자 모델에 같은 클래스 메소드를 추가 할 필요가 부착되어있는 모든 지역의 코드를 끌어 범용 GROUP_CONCAT의 작업을 얻으려면 그 자리에 약간의 코드 만 있으면 다음은 전자 메일 주소로 정렬 된 모든 사용자를 가져옵니다.

ruby > User.regions_listing 
=> [#<User email: "[email protected]">,#<User email: "[email protected]">,#<User email: "[email protected]">,#<User email: "[email protected]">,#<User email: "[email protected]">] 

이 리턴 각 객체는에게 regions_users 테이블을 통해 해당 사용자에게 부착 영역에 대한 부호의 연접 그룹리스트를 제공하는 #regions_list 속성 판독기를 갖는다.

가 #map 간단한 호출을 알 수있다 :이 때문에 적절한 AREL 백업 AR 방법을 사용하고 있는지

ruby > User.regions_listing.map { |u| [u.email, u.regions_list] } 
=> [["[email protected]", "0,1,2,3,4,5"], ["[email protected]", "1,2,5"], ["[email protected]", "0,4"], ["[email protected]", "3"], ["[email protected]", "2,3,4,5"]] 

참고는 체인 가능하다. 즉, ".regions_listing"을 User 모델에 대한 AR 쿼리의 끝 부분에 추가 할 수 있으며 쿼리를 가져온 User 개체에 대한 그룹 연결 메서드/데이터를 제공합니다.

등으로

:

ruby > User.where("users.email like 'b%'").regions_listing.map { |u| [u.email, u.regions_list] } 
=> [["[email protected]", "0,4"], ["[email protected]", "2,3,4,5"]] 

그리고 당신은 또한 두 지역 0 영역 (4)에 연결된 모든 사용자를 찾을 예를 들면,이 HAVING 사용하여 제조 #regions_list 필드에 데이터를 얻을 수 있습니다 :

ruby > User.regions_listing.having("regions_list LIKE '%0%4%'").map { |u| [u.email, u.regions_list] } 
=> [["[email protected]", "0,1,2,3,4,5"], ["[email protected]", "0,4"]] 
관련 문제