[英]Rails: query postgres jsonb using where error
我的 postgres performances
表中有一個名為authorization
的 jsonb 列,我將用戶的 uuid 存儲為鍵,並將其授權級別存儲為值,例如
{ 'sf4wfw4fw4fwf4f': 'owner', 'ujdtud5vd9': 'editor' }
我在我的Performance
模型中使用以下 Rails 查詢來搜索用戶是所有者的所有記錄:
class Performance < ApplicationRecord
def self.performing_or_owned_by(account)
left_outer_joins(:artists)
.where(artists: { id: account } )
.or(Performance.left_outer_joins(:artists)
# this is where the error happens
.where("authorization @> ?", { account => "owner" }.to_json)
).order('lower(duration) DESC')
.uniq
end
end
其中account
是用戶的帳戶 uuid。 但是,當我運行查詢時,出現以下錯誤:
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "@>")
LINE 1: ..._id" WHERE ("artists"."id" = $1 OR (authorization @> '{"28b5...
生成的 SQL 是:
SELECT "performances".* FROM "performances"
LEFT OUTER JOIN "artist_performances" ON "artist_performances"."performance_id" = "performances"."id"
LEFT OUTER JOIN "artists" ON "artists"."id" = "artist_performances"."artist_id" WHERE ("artists"."id" = $1 OR (authorization @> '{"28b5fc7f-3a31-473e-93d4-b36f3b913269":"owner"}'))
ORDER BY lower(duration) DESC
我嘗試了幾件事,但不斷收到相同的錯誤。 我哪里錯了?
根據原始問題中的評論,解決方案是將authorization
用雙引號括起來。 例如:
.where('"authorization" @> ?', { account => "owner" }.to_json)
->>
運算符以文本形式獲取 JSON 對象字段。
所以看起來你需要這個查詢:
left_outer_joins(:artists).
where("artists.id = ? OR authorization ->> ? = 'owner'", account, account).
order('lower(duration) DESC').
uniq
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.