Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 routes and using GET to create clean URLs?

I am a little confused with the routes in Rails 3 as I am just starting to learn the language. I have a form generated here:

  <%= form_tag towns_path, :method => "get" do %>
    <%= label_tag :name, "Search for:" %>
    <%= text_field_tag :name, params[:name] %>
    <%= submit_tag "Search" %>
  <% end %>

Then in my routes:

  get "towns/autocomplete_town_name"
  get "home/autocomplete_town_name"

  match 'towns' => 'towns#index'
  match 'towns/:name' => 'towns#index'

  resources :towns, :module => "town"
  resources :businesses, :module => "business"

  root :to => "home#index"

So why when submitting the form do I get the URL:

/towns?utf8=✓&name=townname&commit=Search

So the question is how do I make that url into a clean url like:

/towns/townname

Thanks,

Andrew

like image 692
Hard-Boiled Wonderland Avatar asked Dec 30 '10 15:12

Hard-Boiled Wonderland


1 Answers

Firstly the routes

resources :towns do
  post 'townname', :on => :collection
end 

or

match "town/:name" => "towns#index", :as => :townname, :via => [:post], :constraints => { :name => /[A-Za-z]/ }

and the form

<%= form_tag townname_towns_path, :method => "post" do %>
  <%= label_tag :name, "Search for:" %>
  <%= text_field_tag :name, params[:name] %>
  <%= submit_tag "Search" %>
<% end %>
like image 80
Bohdan Avatar answered Sep 30 '22 17:09

Bohdan