Noob search question

Hi All,

I am beginning to think that mt brain doesnt speak Ruby(or rails)!

I am attempting to build the most basic search function imaginable - Search within the database for a particular location


@locations = Location.find(:all, :conditions => ["location like ?", "%#{@search_text}%"])

In my view I just put my basic scaffolded view from show, reasoing that this should return that exact result

View <h2>Find Results</h2> <% for column in Location.content_columns %> <p>   <b><%= column.human_name %>:</b> <%=h @location.send( %> </p> <% end %>

Help how do I resolve basic results like this? More properly I know it should return a table of all the close matches, but anything other than nasty NOMethoError# would be great!

First of, this find looks much cleaner and is more scure as everything is escaped by Rails:

@locations = Location.find(:all, :conditions => ["location like %?%", @search_text])

For the view: forget that scaffold stuff, it keeps you from learning how to do it yourself. in your current view, you loop through the Models *column headers* and not the returned results in @location. <%=h @location.send( %> will therefore not return each results content, but throw an error i guess ... not too fit in ruby myself, but been i while since touched scaffold for the reason mentioned above.

<h2>Search Results</h2>

<% @locations.each do |loc| %> <p> <b><%= loc.location %></b> </p> <%end%>

...something like this, errors to be expected :smiley:

Note: i'm kind of new to Rails too so maybe my explanations where plain bullshit. Excuse me.


For whatever reason my last post didnt show up!

Here is where I am with this now. The 'Location like %?%....'

Would result in a MySQL error like

Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%'Hicom Room'%)'

So the wildcards are on the wrong side of the quotes

If I hard code @search_text = 'Hicom Room' and take the wildcards out it works fine So... one step close I guess!


I done know if this is interesting to anyone esle, of if they can just shed some light on this.

I hasd been using a helper as the input for my search string:

<%= start_form_tag :action => 'find' %> <%= text_field :search, :search %> <%=submit_tag 'Find' %>

This turned out to be the cause of the Mysql error below as it seemed to be adding whitespace and new line characters, as soon as I changed the filed to be :

<%= start_form_tag :action => 'find' %> <input id="search" name="search" value=""> <%=submit_tag 'Find'%>

it worked straight away!

Any suggestions?