1

I have a entity in my database that have multiple fields. I need search in this entity based if a certain input it's contained in certain fields, by example

Entity Car

  • model_name
  • owner

I want search like this (a pseudo sql idea)

 Select * FROM Car WHERE (LIKE model_name = "%maz%" OR LIKE owner = "%maz%")

I've tried with the find method but it's not work

searched_string = "%maz%"
Car.find(:all, :conditions => {model_name: searched_string, owner: searched_string})

How to achieve this?

1 Answer 1

3

When using the conditions option in an ActiveRecord query, the resulting SQL will be generated for an exact match. Additionally, each condition you add will be joined using an AND, not an OR.

That being said, the SQL generated by your query above likely looks like this:

SELECT * FROM Car WHERE (model_name = "%maz%" AND owner = "%maz%")

To get the query you are looking for, you'll have to hand-write the SQL for the WHERE clause.

Car.where("model_name ILIKE :q OR owner ILIKE :q", q: "%maz%")

NOTE: I'm using the more modern ActiveRecord syntax above.


Some good news is that Rails 5 will include support for "or" queries.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Glad it worked. Regarding the case-insensitive search, you'll notice that I used the ILIKE keyword rather than the LIKE keyword-- this is exactly for doing a case-insensitive search. So use ILIKE instead of LIKE and you'll be good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.