简体   繁体   中英

How to query Postgresql HSTORE in ruby on rails

I need to find all the notifications of a user of type interview.

app/models/notification.rb :

class Notification < ActiveRecord::Base
  belongs_to :user

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

Searching in google there's not too much information, so I followed this tutorial : but was unable to query the DB as stated there in the example:

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

I tried

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

But I got the error:

*** 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')`

The correct way to query the HSTORE is being careful of the single quotes around the key, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM