Help on Simple Search

Hey there,

I realize this is simple but I am unable to find a working example
anywhere. I just need an example of how to submit a search value from a
form, and have a query run on that value using Rails. For example:

BASIC form…one field. Enter in a last name (e.g. ‘Smith’) and have a
query run against a table and return rows where a field (LastName) is
‘Smith’.

Where I am hung up is the actual passing of the form value (let’s say
the field name is ‘lastname’) to my controller
(student_search_controller.rb) to the method which will execute the
query.

In my form, I have:

<%= start_form_tag :action => ‘searchresults’ %>

Last Name
<%= text_field 'student', 'searchfield' %>

<%= submit_tag "Search" %> <%= end_form_tag %>

In my Controller I have:

def searchresults

lastname = params[:lastname]
@students = Student.find(:all,
                        :conditions => ["LastName = :lastname", 

params])
end

However, I get the following error:

ActiveRecord::PreparedStatementInvalid in Student_search#searchresults

wrong number of bind variables (4 for 1) in: LastName = :lastname

Can anyone provide a simple example? I can execute the query by
hard-coding it in my searchresults method, but obviously…that’s not
really what I need here.

Thanks!
Grant

Grant GBrown wrote:

Hey there,

P

Can anyone provide a simple example? I can execute the query by
hard-coding it in my searchresults method, but obviously…that’s not
really what I need here.

Your data should actually be under params[:student][:searchfield],
as that is what you named the textfield (see the API docs). You
can also inspect the structure for more information:

$stderr.puts "Params: #{params.inspect} # Shows in webrick output

Now, generally, all Rails questions should go to:

http://lists.rubyonrails.org/mailman/listinfo/rails

Post there if you have any follow-ups! :slight_smile:

Thanks!
Grant

E