嗨,哈希属性的热门活动

问题描述 投票:0回答:1

我正在尝试根据事件中的特定属性(“值”)找到获取数据库中前 5 个(按计数)事件的正确方法。我还使用了 hightop gem 来更容易获得前 5 名。

如果我使用:

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

这可行,但按事件名称排序。我想按该事件中存在的“价值”属性进行排序。典型事件如下:

<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)

但这会产生以下错误:“无法下标键入文本,因为它不是数组”。有没有办法真正做我想做的事?

ruby-on-rails ruby activerecord rails-activerecord ahoy
1个回答
0
投票

原因是

properties
列是一个 JSON 列,因此使用 JSON 提取运算符 (
->>
) 和
Arel.sql()
方法来包装
properties->>'value'
表达式将是一种方法:

Ahoy::Event.where(time: Date.today.beginning_of_month..Date.today.end_of_month).top(Arel.sql("properties->>'value'"), 5)
© www.soinside.com 2019 - 2024. All rights reserved.