我需要找到面试类型的用户的所有通知。
app/models/notification.rb
:
class Notification < ActiveRecord::Base
belongs_to :user
hstore_accessor(
:data,
path: :string,
message: :string,
type: :string
)
end
在谷歌中搜索没有太多信息,所以我遵循了本教程:但无法查询数据库,如示例中所述:
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')`
查询 HSTORE 的正确方法是注意键周围的单引号,如下所示:
user.notifications.where(
"data -> 'type' = :key",
key: Interview::NOTIFICATION_TYPE
).count