ruby-on-rails - rails : Cast string field to integer in where clause

标签 ruby-on-rails postgresql

postgres 数据库中,我在 orders 表中有一个字符串字段 code。该字段包含“COA-38-A”、“EFILLDIRT”和“HE60LS-A”等值。 UI 上有一个表单可以根据 code 过滤订单,并且该字段中只允许使用整数值。

查询应按 code 字段中的整数值过滤订单,即如果输入 30,则查询应返回代码为“COA-38-A”和“HE60LS-A”的订单,因为查询包含 >=

我尝试在查询中添加 ::integer :

Order.where('code::integer >= ?', params[:code])

但出现以下错误:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer

有没有办法只按整数值进行过滤?

最佳答案

试试这个?

Order.where("regexp_replace(0||code, '[^0-9]+', '', 'g')::integer >= ?", params[:code].to_i)

关于ruby-on-rails - rails : Cast string field to integer in where clause,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44151914/

相关文章:

sql - 将所有 Controller 操作包装在 Rails 中的事务中

ruby-on-rails - 我是否正确地重新索引了这个 Sphinx 索引?

ruby-on-rails - 是否有用于将整个目录从 HTML 转换为 HAML 的 bash 命令?

sql - 如何用数据将数组更改为jsonb?

ruby-on-rails - 这些 rails generate 命令有何不同? rails generate 的基本含义是什么?

ruby-on-rails - 带有 git remote 的 Gem 文件在 heroku push 上失败

postgresql - 基于postgres数据库在数据仓库中实现继承的最佳方法

sql - 按更近的距离获取 MIN MAX 分组

php - 错误 : invalid input syntax for type timestamp with time zone: "09/03/1943 01:00:00 MWT"

node.js - 如何使用 prisma 和 postgresql 处理条件准备语句?