Home > database >  Search model in Ruby on Rails with multiple words query string
Search model in Ruby on Rails with multiple words query string

Time:04-12

I have a Ruby on Rails app, and I am trying to perform a search through a model. From the front end, I am passing the query string.

In courses_controller.rb I have the following code:

 ...
 Course.where("courses.name ILIKE ?", "%#{params[:search]}%")
 ...

If params[:search] is equal to something like "marketing", it will retrieve the item with name "marketing course". But if params[:search] is equal to "marketing course", nothing is retrieved.

How can I perform search with multiple words?

Thanks a lot.

CodePudding user response:

Probably you need to check the value of params[:search]

Spaces in query string can be encoded with ' ' or ' ' chars. So, in this case u are trying to find something like 'marketing course' or 'marketing course' which doesn't exists in database.

CodePudding user response:

Turns out I found a way:

 ...
 Course.where("courses.name ILIKE ?", "%#{params[:search].tr('-', ' ')}%")
 ...

It was adding unwanted "-" between words.

  • Related