简体   繁体   中英

Case-insensitive search in Rails model ReWorded

Yes there is a question almost exactly like this, but I don't think it was answered in a rails way. It's so not DRY it hurts Case-insensitive search in Rails model

I want to search my postgresql database for a product based on name. I also might want to search the same database for a customer.

So I make use of the suggestions in the previous question. I have a function in my products table Product.find_by_name #takes the name and finds just as the previous answer suggests.

Easy as! Now how about customers...

Customer.find_by_contact_name
Customer.find_by_email_address
Customer.find_by_company_name
Customer.find_by_phone
Customer.find_by_contact_name_and_phone
Customer.find_by_industry_id_and_contact_name  #the insdustry_id is not text so it can't be found. 
# Ahh snot I forgot a few.
Customer.find_by_contact_name_and_company_name
Customer.find_by_contact_name_and_email_address
Customer.find_by_contact_name_and_phone
Customer.find_by_industry_id_and_email_address
...

Each one of these had to be hard coded. And when I needed another one, I had to open Customers, copy the code, and create a new function.. Because I didn't know if the values would be integers or strings, or dates.

I'm sort of looking for a way to not have to implement this for every model and every iteration of search I might like to do at some point in the future.

I would like to say thanks for the answers to the other question. They just don't seem very "Rails" like, and I was hoping for something more. Fingers crossed, someone with more than 4 months in, can point me to a real DRY.

Are you trying to search across all of these attributes at the same time? If so, you might want to try using a search engine like Thinking Sphinx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM