【问题标题】:Rails 5.1.5: lambda with two params for JSONB column data filteringRails 5.1.5:带有两个参数的 lambda,用于 JSONB 列数据过滤
【发布时间】:2018-02-19 01:02:11
【问题描述】:

我有 position_positions 表,其中 JSONB 列名为 data。我的 lambda 有点卡住了,它应该按 ptypedata 列的值进行过滤。

我有两个参数的 lambda(这是强制性的)的方法如下所示:

def find_ptype
  -> (column, formated_value) { 
    where("position_positions.data->>'ptype' = ?", "#{formated_value}%")
  }
end

但是我得到了这个错误:NoMethodError (undefined method "where" for #

另一个尝试是与 Arel:

def find_ptype
  ->(column, formatted_value) {
    Arel.sql("JSON_EXTRACT(#{column.field}, '$.ptype') = '#{formatted_value}'")
  }
end

但我收到此错误:

ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR:  function json_extract(text, unknown) does not exist
LINE 1: ...ND "position_positions"."deleted_at" IS NULL AND (JSON_EXTRA...
                                                             ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
: SELECT COUNT(*) FROM "position_positions" WHERE "position_positions"."type" IN ('Position::Outdoor') AND "position_positions"."deleted_at" IS NULL AND (JSON_EXTRACT(data->>'ptype', '$.ptype') = 'billboard')):

在上面的这个例子中,我试图为我的data->>'ptype' 传递billboard 值,但是得到了那个错误。

我该如何修正我的方法来过滤我的 JSONB 列值?我会很高兴得到任何提示。谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby postgresql lambda


    【解决方案1】:

    我的案例与ajax-datatables-rails gem 有关,似乎这是解决方案:

    def find_ptype
     ->(column, formated_value) {
       Arel.sql("position_positions.#{column.field} = '#{formated_value}'")
     }
    end
    

    当我将data->>'ptype' 作为列和billboard 作为formated_value 传递时,我需要添加position_positions 表并删除JSON_EXTRACT 部分。

    我希望这对其尝试通过 JSONB 列值实现搜索的其他人有所帮助。

    【讨论】:

      【解决方案2】:

      以下代码可能对您有所帮助。

      def find_ptype
        -> (column, formated_value) { 
          where("position_positions.data->>'ptype' = ?", "%#{formated_value}%")
        }
      end
      

      您错过了开盘百分比。这导致了上述问题。

      JSON and JSONB

      我运行了你的代码,发现它运行不正常。

      def find_ptype
          -> (column, formated_value) { 
            # where("position_positions.data->>'ptype' = ?", "%#{formated_value}%")
            where("payload->>'kind' = ?", "%#{formated_value}%")
          }
        end
      

      显示如下错误:

      用下面的代码替换上面的代码就可以了。

      scope :find_ptype, ->(column, formated_value){ 
          where("payload->>'kind' LIKE ?", "%#{formated_value}%")
        }
      

      输出是:

      【讨论】:

      • 谢谢,但我一直收到同样的错误:NoMethodError (undefined method "where" for #
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      相关资源
      最近更新 更多