Topic: Search best practices

I want to allow users to search for an event by title. I was thinking find_by_sql and a "like" operator in the where clause, but I'm guessing there might be a better more ROR way of doing this.

Anyone got tips for building search the right way the first time?

Re: Search best practices

You can use conditions in the find like this:

Event.find(:all, :conditions => ['title LIKE ?', '%' + params[:query] + '%'])

Railscasts - Free Ruby on Rails Screencasts

Re: Search best practices

I think I should just get your phone number and email. You're too damn helpful :-)

So you'd say it's a reasonable approach to implement very basic search like this?

Re: Search best practices

Yak wrote:

I think I should just get your phone number and email. You're too damn helpful :-)

So you'd say it's a reasonable approach to implement very basic search like this?

If you're only searching on a small number of columns, then I don't see anything wrong with that approach. You might want to go more sophisticated (i.e. fulltext searching, sorting by relevance) in the future but this is a reasonable interim way to go smile

vinnie - rails forum admin

Re: Search best practices

Ok here come the stupid questions :-)

Here is my little search form:

<%= form_tag :controller => "event", :action => "search" %>
  <%= text_field "event", "query" %><%= submit_tag "Search" %>
<%= end_form_tag %>

And here is my controller:
def search
  @searchresults = Event.find(:all, :conditions => ['name LIKE ?', '%' + params[:query] + '%'])
end

Getting this:
can't convert nil into String

RAILS_ROOT: ./script/../config/..
Application Trace | Framework Trace | Full Trace

#{RAILS_ROOT}/app/controllers/event_controller.rb:31:in `+'
#{RAILS_ROOT}/app/controllers/event_controller.rb:31:in `search'


So is it getting 'nil' for params[:query] or is it the '+' it doesn't like?

Re: Search best practices

If I do either of the following (playing with single quotes) the page renders, but deoesn't seem to grab any results...using a value I tested in a hand coded query in Query Browswer:

@searchresults = Event.find(:all, :conditions => ['name LIKE ?', '%' + 'params[:query]' + '%'])

@searchresults = Event.find(:all, :conditions => ['name LIKE ?', '% + params[:query] + %'])

Re: Search best practices

The problem is params[:query] is nil. You need to use text_field_tag instead of text_field so it doesn't put the query in the params[:event] hash:

<%= text_field_tag :query %>

Railscasts - Free Ruby on Rails Screencasts

Re: Search best practices

Or you can use params[:event][:query] if you want to keep your old textfield.

Re: Search best practices

Thanks guys. I got it working using the text_field_tag approach.

http://www.racebucket.com/home/show

This will suffice for the time being. Next step is to add filtering to the list views when browsing events by state or type.