【问题标题】:How to query Postgresql HSTORE in ruby on rails如何在 ruby​​ on rails 中查询 Postgresql HSTORE
【发布时间】:2017-04-03 21:30:24
【问题描述】:

我需要查找类型采访用户的所有通知。

app/models/notification.rb:

class Notification < ActiveRecord::Base
  belongs_to :user

  hstore_accessor(
    :data,
    path: :string,
    message: :string,
    type: :string
  )
end

在 google 中搜索并没有太多信息,所以 我关注了this tutorial:但无法按照示例中的说明查询数据库:

User.where("preferences -> newsletter = :value", value: 'true')

我试过了

user.notifications.where('data -> type = :key', key: Interview::NOTIFICATION_TYPE)

但我得到了错误:

*** ActiveRecord::StatementInvalid Exception: PG::UndefinedColumn: ERROR:  column "type" does not exist
LINE 1: ...WHERE "notifications"."user_id" = $1 AND (data -> type = 'IN...
                                                             ^
: SELECT COUNT(*) FROM "notifications" WHERE "notifications"."user_id" = $1 AND (data -> type = 'INTERVIEW')`

【问题讨论】:

    标签: ruby-on-rails postgresql-9.1 hstore


    【解决方案1】:

    查询 HSTORE 的正确方法是注意键周围的单引号,如下所示:

    user.notifications.where(
      "data -> 'type' = :key",
      key: Interview::NOTIFICATION_TYPE
    ).count
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-10
      • 2015-01-25
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多