如何在rails上的ruby中查询Postgresql HSTORE

时间:2017-04-03 21:30:24

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

我需要找到面试类型用户的所有通知。

app/models/notification.rb

class Notification < ActiveRecord::Base
  belongs_to   :user

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

在谷歌搜索没有太多信息,所以 我跟着this tutorial:但无法按照示例中的说明查询数据库:

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

我试过

(byebug) 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')

1 个答案:

答案 0 :(得分:0)

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

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