Ruby on rails Rails:使用where error查询postgres jsonb
我在我的postgresRuby on rails Rails:使用where error查询postgres jsonb,ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,我在我的postgresperformances表中有一个名为authorization的jsonb列,其中我将用户的uuid存储为密钥,并将其授权级别存储为值,例如 { 'sf4wfw4fw4fwf4f': 'owner', 'ujdtud5vd9': 'editor' } 我在我的性能模型中使用以下Rails查询来搜索用户是所有者的所有记录: class Performance < ApplicationRecord def self.performing_or_own
performances
表中有一个名为authorization
的jsonb列,其中我将用户的uuid存储为密钥,并将其授权级别存储为值,例如
{ 'sf4wfw4fw4fwf4f': 'owner', 'ujdtud5vd9': 'editor' }
我在我的性能
模型中使用以下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
生成的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
我尝试了好几件事,但总是犯同样的错误。哪里出错了?操作符将JSON对象字段作为文本获取 看来您需要这个查询:
left_outer_joins(:artists).
where("artists.id = ? OR authorization ->> ? = 'owner'", account, account).
order('lower(duration) DESC').
uniq
根据原始问题中的注释,解决方案是将
授权
用双引号括起来。例如:
.where('"authorization" @> ?', { account => "owner" }.to_json)
您在哪种型号中使用此代码?哪个表有
授权
列?在性能
型号/表中,哪个表有授权
列。我将把它添加到问题中。将授权用引号括起来可以解决问题吗?您是否尝试过以下方法:left\u outer\u joins(:artists)。where(artists:{id:account})。或者(left\u outer\u joins(:artists)。where(“authorization->?='owner',account))
@crtag您找到了吗。我必须将授权
用引号括起来,而且必须用双引号括起来。单引号仍然会抛出错误。如果您愿意,发布一个答案:。where(“'authorization”@>?”,{account=>“owner”}.to_json)
,我会给您检查。即使使用->>操作符,我仍然会得到相同的错误。我最好的猜测是关于我是如何使用引用语的
.where('"authorization" @> ?', { account => "owner" }.to_json)