juliangonzalez
juliangonzalez

Reputation: 4381

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

Upvotes: 2

Views: 3666

Answers (1)

juliangonzalez
juliangonzalez

Reputation: 4381

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

Upvotes: 2

Related Questions