This is my first attempt at trying to implement a simple search form in my rails app, New to rails so forgive me if I have made some major mistakes
I have a search form that looks like this
<%= form_tag({:controller => 'search', :action => 'search'}, {:method => 'get'}) do |s| %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search" %>
<% end %>
My controller
def search
@countrysearch = Recipe.find(params[:search])
end
For now i am outputting my results like so
<h4>output</h4>
<%= @countrysearch %>
I am getting an output but if i search for a word like Wales, i get an error saying could not find by id, but if i search for an id like 17 then i get
#<Recipe:0x97b0fa8>
I have looked into the find_by_sql method but my understanding of this is not there yet, im unsre of the syntax to search dependent on the string I enter, though I guess that doesn’t matter as the params are the content of the search field?
If any can help then it would be much appreciated
Thanks
The model
findmethod (Recipe.find()) expects the numeric id of the instance (a specific recipe). But it looks like you’re searching by country name. There are lots of ways to do this in Rails. First, however, I assume that your recipe model has an attribute like “country” whose values are like “Wales”.If so, then you could make your search method like this:
Or alternatively you could use the new approach in Rails 3
Don’t use
find_by_sql— it will work, and it’s not bad, but then you’re missing some of the main power of Rails.There are a couple of other things worth mentioning:
@countrysearchinstance variable, test for nil usingif @countrysearch.nil?or for the positive caseif @countrysearch.present?Recipeback, but a collection of them — in your view, iterate using<% @countrysearch.each do |recipe| %>
<%= recipe.name %>
…
<% end %>
Recipe.find_all_by_country