【发布时间】:2020-02-23 20:26:05
【问题描述】:
我的 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列? -
在
performance模型/表中,其中有authorization列。我会将其添加到问题中。 -
将授权用引号括起来能解决问题吗?
-
你试过了吗:
left_outer_joins(:artists).where(artists: { id: account } ).or(left_outer_joins(:artists).where("authorization ->> ? = 'owner'", account)) -
@crtag 你找到了。我必须将
authorization用引号括起来,并且它必须是双引号。单引号仍然会引发错误。如果您愿意,请发布答案:.where('"authorization" @> ?', { account => "owner" }.to_json),我会给您支票。
标签: ruby-on-rails postgresql activerecord