Calin
Calin

Reputation: 6847

Rails routes related to a search form

On my latest web site I have a search form defined like this:

= form_tag search_path(:termen), :method => :get do
  = text_field_tag :termen, params[:termen]
  = submit_tag "Search »"

And a route:

# search
get "search(/:termen)" => "articole#cauta", :as => :search

I want when I press the search button to be get to a url like:

http://www.mysite.com/search/[the_termn_that_was_typed]

So for example when I am searching "vampires" I should get:

http://www.mysite.com/search/vampire

Any clues on this one?

Thank you a lot,

Upvotes: 2

Views: 6680

Answers (2)

Anton
Anton

Reputation: 927

I think that RESTful way of doing this is to make redirect of posted request to get request with constructed url you want it to be.

Here are two routes

resources :articles do
  collection do 
    get :search, :action => 'search_post', :as => 'search_post'
    get 'search/:q', :action => 'search', :as => 'search'
  end
end

Now in the controller you redirect the post request to get request

def search_post
  redirect_to search_articles_path(params[:q])
end

As a result of submitting the form user ends up on the url

http://www.mysite.com/articles/search/vampire

Upvotes: 6

tsherif
tsherif

Reputation: 11710

I don't think you can get around this when using a form directly, because that's just how the parameters are submitted. You could do it with a bit of javascript though. I'll offer a solution that I feel is a bit clunky, and you can decide if it's worthwhile or not.

First the js (using jQuery):

$(".search_submit").click(function(){
  var button     = $(this);
  var form       = button.closest("form");
  var action     = form.attr("action");
  var text_field = form.find(".search_text");
  var value      = text_field.val();

  window.location = action + "/" + value;
  return false;
});

And then your view code would just need to add the appropriate classes:

= form_tag search_path(:termen), :method => :get do
  = text_field_tag :termen, params[:termen], :class => "search_text"
  = submit_tag "Search »", :class => "search_submit"

Hope that helps.

Upvotes: 1

Related Questions