Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Dynamic 'Where' clause

I have a search field where the user can enter "Param1" and my controller contains:

Model.where('column_name LIKE ?', "%#{search_field}%")

This is converted to:

SELECT ... FROM table WHERE column_name LIKE '%Param1%'

This works fine if the user enters "Param1" but I want make it comma separated search field.

So if the user enters "Param1,param2" or "Param1,Param2,Param3" the WHERE LIKE clause should work, My idea is to split the string based on ',' and have absolutely no idea on how to build the Model.where clause here, since it can be 1 parameter or 4.

like image 317
LutherSmi Avatar asked Feb 04 '26 08:02

LutherSmi


1 Answers

In case you're using PostgreSQL, you can use ANY passing the mapped array of params:

Model.where('name LIKE ANY(array[?])', params.split(',').map { |val| "%#{val}%" })
# SELECT "models".*
# FROM "models"
# WHERE (name LIKE ANY(array['%param1%','%param2%']))
like image 161
Sebastian Palma Avatar answered Feb 05 '26 22:02

Sebastian Palma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!