Question

I am trying to implement a search function searching through all the fields in a model to find matching records.

I would like to split my where query at the OR's onto different lines. How can I do this?

This is a working example:

u = User.where("LOWER(id) LIKE ? OR LOWER(name) LIKE ?", s, s)

But I want to implement a lot more fields so to make things more readable, I would like to split the where's to different lines e.g.:

u = User.where("LOWER(id) LIKE ?", s)
u << User.where("LOWER(name) LIKE ?", s)
u << User.where("LOWER(surname) LIKE ?", s)

This works but may return duplicate records for instance if a name and surname is the same etc. I could run this and then remove all duplicates, but the data-set is too big to iterate over it afterwards. I also need this in an ActiveRecord::Relation to perform other commands on it.

Is there a way to do this, or should I just keep it all on one line?

Was it helpful?

Solution

If all your point is readability, I'd suggest to take 2 variables -

query_statement = "LOWER(id) LIKE ? OR " + 
                  "LOWER(name) LIKE ? "


query_variables = s,s

and then use these two variables in the actual query :

u = User.where("#{query_statement}, #{query_variables}")

Hope this helps !!

If you find some better option, Do post here! Thanks !

OTHER TIPS

Try this also.

with_names = User.where("LOWER(name) LIKE ?", s)
with_surnames = User.where("LOWER(surname) LIKE ?", s)
@result = with_names | with_surnames
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top