[英]How to search using like in ruby
I have 2 records in keyskill tables name "SAP FICO" and "FICO SAP". 我在键技能表中有2条记录,分别为“ SAP FICO”和“ FICO SAP”。 When i search the record with "FICO SAP". 当我使用“ 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表数据。(在表中这样创建)
<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. 然后只需使用filtered_skills
即可检索它们。
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. 因此,我们可以在所有条件下使用and
。
[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 如果您希望此搜索不区分大小写,那么如果使用的是postgresql,则可以按以下方式重写where
.where("name ilike '%#{term}%'")
(ilike = case Insensitive LIKE). (ilike =不区分大小写的LIKE)。 But this method only exists for postgresql, so for any other database you would use the following: 但是此方法仅适用于postgresql,因此对于任何其他数据库,您将使用以下方法:
.where("lower(name) like '%#{term.downcase}%'")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.