Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from a form through a query string in Rails

I am creating an application with a search feature, and I would like have it set up similarly to Google or Twitter search, where there is a landing page with a search form at the root URL and then data from this form is passed through a query string, which forms the URL for the results page (for example: www.domain.com/search?query=my+search+query).

As of now, I know how to pass the data from the search for using the params hash, but I would like to know how to pass the data and access it using a query string.

My best guess is the it is done through the routing, where you include something like the following in the routing for the search action:

:query => params[name_of_search_form_element]

then access this value in the controller using the params hash, but I'm not sure if this is the best way. Any thoughts? Thanks!

like image 317
rymodi Avatar asked Jul 21 '10 16:07

rymodi


1 Answers

I would suggest the following procedure for setting up a simple search.

  1. Create a search route in your 'routes.rb' file. This allows you to intercept all calls to paths starting with 'search' like http://www.example.com/search.

    map.search 'search', :controller => 'search', :action => 'search'
  2. Create the regular search form in the view, like the following example.

    You can see the helper method search_url which is provided by your route configuration. This helper creates a url pointing directly at your mapped search page. You should also notice the :method => 'get' call, which will show all your send parameters as part of the url. Additionally, we do not want to send the name of the search button in the url, so we set :name => nil. We will also display the currently searched term in the textfield. The search parameter typed in by the user, will be available to us in the controller through params[:search]which is the name of the search field.

    <%- form_tag(search_url, {:method => 'get'}) do -%>
        <%= text_field_tag(:search, params[:search]) >
        <%= submit_tag('Search', :name => nil) >
    <%- end -%>
  3. Now we can set up the search controller.

    As you can see, if we find a search parameter, we will try to find users by that name. If we don't have a search parameter, all users will be displayed in the resulting view.

    class SearchController
      def search
        if params[:search].present?
          @users = User.find(:all, :conditions => ['name LIKE ?', params[:search]]))
        else
          @users = User.find(:all)
        end
      end
    end
  4. All you have left is to create the 'search.html.erb' file under 'view/search/' and display each user in the @users variable.

If I didn't forget something, you should be able to set up a simple search form by now. Good luck searching!

like image 95
murphyslaw Avatar answered Nov 15 '22 05:11

murphyslaw