0

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?

4

2 回答 2

1

如果您的重点是可读性,我建议采用 2 个变量 -

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


query_variables = s,s

然后在实际查询中使用这两个变量:

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

希望这可以帮助 !!

如果您找到更好的选择,请在此处发布!谢谢 !

于 2013-05-29T10:41:09.363 回答
0

也试试这个。

with_names = User.where("LOWER(name) LIKE ?", s)
with_surnames = User.where("LOWER(surname) LIKE ?", s)
@result = with_names | with_surnames
于 2013-05-29T13:27:30.260 回答