rico_mac
rico_mac

Reputation: 888

search logic in Rails, making it more precise hopefully without a gem

is there a way to improve the search logic in Rails. for example, currently if i search 'red leather' the search matches red OR leather. How could you improve the search logic so that if i search 'red leather' I don't get 'red dog' but say 'red leather coat'. Ideally I would like to do this without a gem. I am using MySQL with rails 4.

an example of my search function is here

 if params[:search_term].present? && params[:search_term].length > 1
   @candidates = @candidates.where("title like ?","%#{params[:search_term]}%")
 end  

UPDATE

I search `'BLACK cat' (There are no black cats in my db), and i am yielded these...

1m Single Bolster Black Velvet 
1m Straight Back Black Velvet 
70cm Straight Back Black Velvet 

the inclusion of cat should negate these results...

Upvotes: 0

Views: 65

Answers (2)

Anthony
Anthony

Reputation: 15967

Your SQL works fine, take a look:

http://ideone.com/Nr1E26

create table tbl(name varchar(20));
insert into tbl(name) values("red dog");
insert into tbl(name) values("red leather");
insert into tbl(name) values("red leather coat");

select * from tbl WHERE name LIKE "%red leather%";

output:

red leather
red leather coat

Upvotes: 1

AJFaraday
AJFaraday

Reputation: 2450

You could try splitting your search term by spaces and calling where for each of them. In Arel this will keep adding filters to your sql with AND...

Assuming your model is called Candidate

query = Candidate
params[:search_term].split(' ').each do |term|
  query = query.where('title like %?%', term)
end
# check it's worked
puts query.to_sql
result = query.all

This should do what you're after. 'red leather' should find 'a red coat made of leather' or 'a leather coat with red pockets'

Although, as a matter of coding practise, this should really be a method in your model, not in the controller. Like so:

def Candidate.search(search_term)
  query = Candidate
  params[:search_term].split(' ').each do |term|
    query = query.where('title like %?%', term)
  end
  result = query.all
end 

Then in your controller:

def search
  @candidates = Candidate.search(params[:search_term])
end

This means that you could then use the method elsewhere, for instance, as part of a rake task, or in the console, which is useful for debugging if you find a problem with it, or want to refine your search method.

Upvotes: 1

Related Questions