2012-03-17 9 views
2

複雑なクエリをレールに書くという論理を理解するためのガイダンスが必要です。複雑なクエリをrailsのアクティブレコードに書く考えを理解するために助けが必要

私は今、私はこのようなフィルタを実装する必要が3つのモデル

Business 

    has_many :customers 
    has_many :transactions 

Customer 
    has_many :transactions 
    belongs_to :business 

Transaction 
    belongs_to :businesss 
    belongs_to :customer 
//transaction model has a attribute amount which tells how much amount has been spent in this particular transaction. 

enter image description here

を持っています。私は理解しやすいスクリーンショットの原因を投稿しています。

編集

すべてのトランザクションは、訪問を意味します。総額とは、費やされた総額を意味する。

+0

顧客訪問に関するデータを保持しているどのようなテーブル(ジャストスケッチ。)?取引は訪問を意味しますか? – forker

+0

@forker Yuppすべての取引は訪問を意味します。 –

答えて

1

私は、ARのフィートの機能になる、優雅な1つのクエリソリューションがあるとは思えません。しかし、1つがあっても、パフォーマンスのために、総使用ランキング値のための重要なビューまたは集計テーブルを作成する必要があります。だから、あなたが通常のARの照会を行うことが材料ビューtotal_spent_ranking(customer_id, rank)を持っていると仮定すると:

Customer.joins(:transaction, :total_spent_ranking).select('customer.id').group_by('customer.id').having('total_spent_ranking.rank > 15 and count(distinct transaction.id) > 10') 
+0

ありがとうございました。とった。完璧な.. –

関連する問題