2012-01-12 10 views
4

私はレールにmysql関数GROUP_CONCATを実行します。 私はアクティブレコードの計算方法を使用しています。 like this self.calculate(:group_concat、:id)self.calculateを使用した際に未定義のエラー

これが正しい方法であるかどうかわかりません。

railsでgroup_concatを実行する方法はありますか? とactiverecordのfindメソッド。

+0

いつでも任意の生のSQLを実行できます。 –

+0

はいsergio、しかし、私はその場合に多くのコードを変更する必要があります。私はアクティブレコードのfindメソッドを使用しているので、すでにクエリを生成しています。 raw SQLクエリを使用せずにgroup_concatを統合する方法はありますか?あなたの応答btwのthnx .. – Hitesh

+0

この問題の実際のSQLクエリをお持ちの場合は、こちらも投稿してください。 –

答えて

0

@Camwayの注釈は、JOINing、SELECTing、およびGROUPingのための適切なRails方法を使用すると簡単に実行できます。例として、ユーザーと地域があるとします。ユーザーは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_nameのとuser_idの整数でテーブルを結合しますフィールド。

私はUserモデルに、このようなクラスのメソッドを追加する必要があり、各ユーザーが接続されているすべての領域のコードを引っ張る汎用GROUP_CONCATの作業を取得するには、次の

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 

ので、ちょうどその場所にコードのビットで、以下は、電子メールアドレスで注文されたすべてのユーザーを引き出します。

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する簡単なコールで見ることができる。

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"]] 

注これは適切なAREL担保AR法を用いているので、それはチェーン可能あること。つまり、".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"]] 
関連する問題