Rails 3路由并使用GET创建干净的URL?

时间:2010-12-30 15:06:57

标签: ruby-on-rails get routes ruby-on-rails-3

我对Rails 3中的路线感到有点困惑,因为我刚开始学习这门语言。我在这里生成了一个表单:

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

然后在我的路线中:

  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"

那么为什么在提交表单时我会得到网址:

  

/城镇UTF8 =✓&安培;名称= townname&安培;提交=搜索

所以问题是如何将这个网址变成一个干净的网址:

  

/城镇/ townname

谢谢,

安德鲁

1 个答案:

答案 0 :(得分:6)

首先是路线

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

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

和表格

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