Search code examples
ruby-on-railsformsruby-on-rails-2

Why won't my simple Rails form_tag search form provide results using the right method?


I am starting small with a search form and trying to get the basics to work. Thanks in advance for any help you can offer.

I'm editing a Rails 2.3 legacy application and revising its old search form. Right now, it just has a field for a text search for locations in my database (by matching against city). When I submit the form, it goes from "URL/search-for-locations" to "URL/search-for-locations?city=Los+Angeles" but doesn't show results. Based on my log, I think the problem is that it's not rendering the right view.

Form Page (index.html.erb

    <% form_tag search_path, :method => 'get' do %> 
    <%= text_field_tag :city, params[:city] %>
    <%= submit_tag "Search", :name => nil %>
    <% end %>

Results Page (results.html.erb)

<% for location in @site_matches %>
<h3><%= location.name %></h3>
<% end %>

Controller (search_controller.rb)

    class SearchController < ApplicationController
    def index
    render :layout => 'mylayout'
    end

    def results
    @site_matches = Location.find(:all, :conditions => ["city = ?", params[:city]])
    render :layout => 'mylayout'
    end 
    end

Log

    Processing SearchController#index (for X at X) [GET]
    Parameters: {"city"=>"Los Angeles"}
    Rendering template within layouts/mylayout
    Rendering search/index
    Completed in 9ms (View: 9, DB: 0) | 200 OK [URL/search-for-locations?city=Los+Angeles]

Routes

    map.resources :search
    map.search '/search-for-locations', :controller => 'search', :action => 'index' 

Again, I appreciate your help with this!


Solution

  • After a lot of trial and error, I discovered that the issue was that my "Results" action wasn't rendering a "get" view. I added the below to my routes:

        map.resources :search, :collection => { :index => :get, :results => :get }
    

    I also changed my form_tag to

        <% form_tag url_for(:controller => 'search', :action => 'results'), :method => 'get' do %> 
    

    And it's all working now!