Techioz Blog

アホイ ハッシュ プロパティ別のトップ イベント

概要

イベントの特定のプロパティ (「値」) に基づいて、データベース内の上位 5 つのイベント (カウント順) を取得する適切な方法を見つけようとしています。このトップ 5 を取得しやすくするために、hightop gem も使用しています。

私が使用する場合:

Ahoy::Event.where(time: Date.today.beginning_of_month..Date.today.end_of_month).top(:name, 5)

これは機能しますが、イベント名で並べ替えられます。そのイベントに存在する「value」プロパティで並べ替えたいと思います。典型的なイベントは次のようになります。

<Ahoy::Event id: 229, visit_id: 318, user_id: 1, name: "Thing", properties: {"episode"=>"1", "title"=>"Test", "value"=>"Thing Ep 1: Test"}, time: "2017-11-02 11:34:10">

私はやろうとしました:

Ahoy::Event.where(time: Date.today.beginning_of_month..Date.today.end_of_month).top("properties['value']", 5)

同様に:

Ahoy::Event.where(time: Date.today.beginning_of_month..Date.today.end_of_month).top("properties ->> 'value'", 5)

しかし、これにより次のエラーが発生します。「配列ではないため、テキストを添え字として入力できません」。実際にやりたいことを実現する方法はあるのでしょうか?

解決策

その理由は、プロパティ列が JSON 列であるため、Arel.sql() メソッドで JSON 抽出演算子 (->>) を使用して、properties->>‘value’ 式をラップする方法です。

Ahoy::Event.where(time: Date.today.beginning_of_month..Date.today.end_of_month).top(Arel.sql("properties->>'value'"), 5)