ruby-on-rails – Rails 3路由并使用GET创建干净的URL?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 3路由并使用GET创建干净的URL?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚开始学习语言时,对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"

那么为什么在提交表单时我会得到这个URL:

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

所以问题是如何使这个url成为一个干净的网址像:

/towns/townname

谢谢,

安德鲁

解决方法

首先是路线
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 %>

猜你在找的Ruby相关文章