1

I have a searchbox to search for products. Each product has a title and is tagged with multiple tags.

I want to be able to search for products by title or tag. In other words if I have a product called "Green Tea" and another product tagged "green, red, blue" and I type "green" into the searchbox, I'd like both products to appear in the search results.

I am using Rails 3, acts_as_taggable_on, Ruby 1.9.2.

robzolkos
  • 2,196
  • 3
  • 30
  • 47

1 Answers1

8

In your controller, the action that displays the search results could look something like this (where :q is your query string from the search box):

def results
  @products = Product.where("title LIKE ?", "%#{params[:q]}%") \
    | Product.tagged_with("%#{params[:q]}%")
end
Jamie Forrest
  • 10,895
  • 6
  • 51
  • 68
  • 1
    I don't understand this syntax... do you need a gem or something? – Noz Jul 11 '12 at 23:14
  • The only gem this relies on is "acts as taggable" where the query above uses the "tagged_with" method. That aside, Jamie is demonstrating how to use Postgres' built in widcard functionality! +1 internets to you sir jamie – bkunzi01 Dec 28 '16 at 19:12