2

In a postgres database I have a string field code in orders table. The field contains values like 'COA-38-A', 'EFILLDIRT' and 'HE60LS-A'. There is a form on UI to filter orders based on code and only integer values are allowed in the field.

The query should filter the orders by integer values in the code field i.e if 30 is entered, the query should return orders with code 'COA-38-A' and 'HE60LS-A' because the query contains >=

I tried adding ::integer in the query:

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

but got the following error:

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

Is there any way to filter by only integer values?

5
  • is COA-3A-8 >= 30?.. Commented May 24, 2017 at 7:44
  • Want to pick 38 form COA-38-A and then 38 >= 30 Commented May 24, 2017 at 7:47
  • I get that - what will you pick from COA-3A-8?.. 3? 38? 8? Commented May 24, 2017 at 7:47
  • all integer values i.e 38 Commented May 24, 2017 at 7:48
  • regexp_replace(code, '[^0-9]+', '', 'g') should get all digits for you Commented May 24, 2017 at 8:03

1 Answer 1

3

try this?

Order.where("regexp_replace(0||code, '[^0-9]+', '', 'g')::integer >= ?", params[:code].to_i)
Sign up to request clarification or add additional context in comments.

5 Comments

Excellent answer. Is it required to do #to_s on params[:code] ?
awful answer - I don't work with rails - I just know how to do it in postgres. And thus Idont know if it should be params[:code].to_s or params[:code] - I used code from OP, but the answer was edited to be with #to_s If to_s stands for to string, I dont think it is needed at all
Yes #to_s is "to string". It's an excellent answer because it solves the OP's problem and you did a creditable job on the syntax. I would suggest params[:code].to_i since in fact the parameter will come in as a string and needs to be substituted as an integer.
Got this after trying: PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: ""
@Arif modified to have leading 0, so empty string would become 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.