I am using filterrfic gem to search an organization in the database. The problem I am facing is when I am searching for an organization whose name starts with National then I get the list of all the organizations which have National in their name. All I want is that it should just search the first word of the name_of_organisation field.
organisation.rb
def self.search(search)
if search
where('name_of_organisation LIKE ?', "%#{search}%")
else
all
end
end
filterrific(
available_filters: [
:search_query
]
)
scope :search_query, lambda { |query|
return nil if query.blank?
terms = query.downcase.split(/\s+/)
terms = terms.map { |e|
(e.gsub('*', '%') + '%').gsub(/%+/, '%')
}
num_or_conds = 1
where(
terms.map { |term|
"(LOWER(organisations.name_of_organisation) LIKE ?)
}.join(' AND '),
*terms.map { |e| [e] * num_or_conds }.flatten
)
}
Currently it displays all the Organisation as below: National Social Service Society for National Serivce
But What I want is that it should only search first word of the name_of_organisation field and display just Nation Social Service
Try changing this line:
where('name_of_organisation LIKE ?', "%#{search}%")
to:
where('name_of_organisation LIKE ?', "#{search}%")
Notice the removal of the first %
in the search string. In this case, %
represents any sequence of 0 or more characters. By removing the first one, it should only search for strings that start with your provided search string.