【问题标题】:Rails: query postgres jsonb using where errorRails:使用where错误查询postgres jsonb
【发布时间】: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 -&gt;&gt; ? = 'owner'", account))
  • @crtag 你找到了。我必须将authorization 用引号括起来,并且它必须是双引号。单引号仍然会引发错误。如果您愿意,请发布答案:.where('"authorization" @&gt; ?', { account =&gt; "owner" }.to_json),我会给您支票。

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

根据原始问题中的评论,解决方案是将authorization 括在双引号中。例如:

.where('"authorization" @> ?', { account => "owner" }.to_json)

【讨论】:

    【解决方案2】:

    -&gt;&gt; 运算符获取 JSON 对象字段作为文本。

    所以看起来你需要这个查询:

    left_outer_joins(:artists).
      where("artists.id = ? OR authorization ->> ? = 'owner'", account, account).
      order('lower(duration) DESC').
      uniq
    

    【讨论】:

    • 即使使用 ->> 运算符,我仍然会遇到相同的错误。我最好的猜测是我如何使用引号
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2019-03-14
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多