[英]How to search using like in ruby
我在鍵技能表中有2條記錄,分別為“ SAP FICO”和“ FICO SAP”。 當我使用“ FICO SAP”搜索記錄時。 我想同時獲得兩個記錄。 如果我搜索,以任何方式獲取此記錄。
我想要這兩個結果,如果我搜索,我嘗試使用如下。 但只取一個。 請幫忙
search = "FICO SAP"
KeySkill.where("name LIKE ?", "%#{search}%")
這是我的Keyskill表數據。(在表中這樣創建)
<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>
一種簡單的處理方法是
search_term = "FICO SAP"
terms = search_term.split
filtered_skills = KeySkill
terms.each do |t|
filtered_skills = filtered_skills.where("name like '%#{term}%'")
end
然后只需使用filtered_skills
即可檢索它們。
這適用於原始搜索詞的每個部分必須以隨機順序出現的情況。 因此,我們可以在所有條件下使用and
。
[編輯:如果您要搜索不區分大小寫的內容]
如果您希望此搜索不區分大小寫,那么如果使用的是postgresql,則可以按以下方式重寫where
.where("name ilike '%#{term}%'")
(ilike =不區分大小寫的LIKE)。 但是此方法僅適用於postgresql,因此對於任何其他數據庫,您將使用以下方法:
.where("lower(name) like '%#{term.downcase}%'")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.