在 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/