简体   繁体   中英

How to search using like in ruby

I have 2 records in keyskill tables name "SAP FICO" and "FICO SAP". When i search the record with "FICO SAP". I want to get both records. Any way to fetch this record if i search.

I want this both as result if i search , i tried using like as below. but it fetches only one. please help

    search = "FICO SAP"
    KeySkill.where("name LIKE ?", "%#{search}%")

This is my Keyskill table data.(created like this in table)

 <KeySkill id: 50, name: "SAP FICO", relevant_experience: "1", created_at: "2019-01-06 08:48:54", updated_at: "2019-01-06 08:48:54", deleted_at: nil> 
<KeySkill id: 51, name: "FICO SAP", relevant_experience: "1", created_at: "2019-01-06 08:48:55", updated_at: "2019-01-06 08:48:55", deleted_at: nil> 

A simple way to handle this would be something like

search_term = "FICO SAP" 
terms = search_term.split 

filtered_skills = KeySkill 
terms.each do |t| 
  filtered_skills = filtered_skills.where("name like '%#{term}%'") 
end 

and then just use the filtered_skills to retrieve them.

This works where each part of the original search term has to be present in a random order. So we can just use and for all terms.

[EDIT: if you want to search case insensitive]

If you want this search to be case independent, you can rewrite the where as follows if you are using postgresql

.where("name ilike '%#{term}%'") 

(ilike = case Insensitive LIKE). But this method only exists for postgresql, so for any other database you would use the following:

.where("lower(name) like '%#{term.downcase}%'")     

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