0

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.

Community
  • 1
  • 1
baash05
  • 4,394
  • 11
  • 59
  • 97
  • Which question are you referring to? (might help w/ context) – Nick Colgan Jun 01 '12 at 01:33
  • added link to other "identical" question – baash05 Jun 01 '12 at 02:11
  • might want to checkout - https://github.com/ernie/ransack - and take a look through some of these? http://railscasts.com/?tag_id=30 - if you hand role your own I would tend to use AREL where syntax `Customer.where("company_name ILIKE ?", params[:company_name]) if params[:company_name].present?` – house9 Jun 25 '12 at 02:45

1 Answers1

1

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

lee
  • 2,351
  • 1
  • 16
  • 18