Richlewis
Richlewis

Reputation: 15374

Search by partial text rails 3

I have a search form that searches multiple columns within my recipe model, at the moment it returns results on full string basis only so if i search lasagne I get a result, however if I search lasa then i get nothing returned. Am i correct in thinking that rather that do a = ? search i need to do a LIKE search? If so I am unsure of the syntax to achieve this.

My current query looks like this

@countrysearch = Recipe.where("dish_name = ? OR country_of_origin = ? OR difficulty = ? OR preperation_time = ?",
params[:search],
params[:search],
params[:search],
params[:search]

)

What do i need to do to get this to search by partial text? or can someone point me to a resource that will advise what syntax to use?

Any help appreciated

thanks

Upvotes: 1

Views: 271

Answers (3)

Thanh
Thanh

Reputation: 8604

If you used postgresql database, check pg_search gem, it support full-text search with many useful options.

Upvotes: 0

platforms
platforms

Reputation: 2726

This can work if you don't end up with a lot of data in your tables. If you will have a lot of recipes, this many LIKE queries on a large dataset can bog down quickly.

I recommend you check out the several search engine integrations for Rails that allow for fuzzy searching. There are several good options that allow you tight integration with Rails models, so that whenever you update your model it also updates your search index.

My favorite is Elasticsearch, using tire in Rails, but many people swear by Solr, Thinking Sphinx, and others. Check out Railscasts for several good search options, any of which solve your problem.

Upvotes: 1

Richlewis
Richlewis

Reputation: 15374

ok think I have found the answer, though if anyone has a better solution please advise

Within the controller I now have

    q = "%#{params[:search]}%"
    @countrysearch = Recipe.where("dish_name LIKE ? OR country_of_origin LIKE ? OR difficulty LIKE ? OR preperation_time LIKE?",
q,
q,
q,
q

)

Upvotes: 1

Related Questions