【问题标题】:Activerecord group count doesn't workActiverecord 组计数不起作用
【发布时间】:2016-05-26 03:14:23
【问题描述】:

我正在尝试编写查询,但找不到正确的结果。我有一个这样的模型:

#<Ahoy::Event id: "007d74fb-6225-4cd5-a725-6e35b2e9a859", visit_id: "34713617-d6f6-4adb-b436-8029a7ea586c", user_id: 3, name: "view", properties: {"id"=>14, "delay"=>500, "action"=>"show", "resource"=>"News", "end_point"=>"news"}, time: "2016-02-12 15:13:05">

它是一个跟踪器,所以我有多个资源,如果我返回同一页面,相同的资源会被跟踪很多时间。

我想知道用户阅读了多少新闻,所以我尝试:

Ahoy::Event.where(user_id:3).group(:properties["resource:news"]).count

更新

我也在尝试

Ahoy::Event.where(user_id:3).where("properties @> (:key => :value)", :key => 'resource', :value => 'Gate').count

** 更新 2 ** 另一个暂定:

Ahoy::Event.where(user_id:3).where("properties --> 'resource': 'Gate'").select("properties #>> 'id' as resource, count('resource')").group("resource")

【问题讨论】:

  • properties 列是什么数据库类型?
  • @SimoneCarletti 这是一个 jsonb
  • JSONB 具有特定的查询语法。你将不得不使用它。我不记得它到底是什么,但stackoverflow.com/questions/30519458/…你可能有一些提示。我不确定您是否可以明确地GROUP BY jsonb 字段值。

标签: ruby-on-rails activerecord


【解决方案1】:

我已经在我的控制台上尝试了 psql,它成功了。

也许你错过了大括号?

Ahoy::Event.where(user_id:3).
  where("properties @> ({:key => :value})", :key => 'resource', :value => 'Gate').
  count

【讨论】:

  • 我注意到我做错了。我还必须按 properties[:id] 分组,我错过了那部分。我对这个查询感到疯狂......我不知道如何按属性 id 分组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
相关资源
最近更新 更多