将rails表单提交到"友好"URL

emh*_*emh 8 forms ruby-on-rails

我在我的网站上有一个搜索表单,允许用户搜索许多不同的方面,如城市,价格范围,大小等.

表单提交为GET,因此表单参数在URL中.

他们最终变得非常丑陋:

/搜索?UTF8 =✓&city_region =温哥华&property_type_id = 1&min_square_footage = 0&max_square_footage = 15000

(它们实际上更糟糕,因为搜索参数是模型的一部分,所以URL中也有很多编码的[和]和)

我想做的是让表单生成一个URL,如:

/搜索/温哥华/办公?square_footage = 0-15000

其中一些参数放在URL路径本身,而其他参数保留在查询参数中(以稍微可读的格式).

在rails应用程序中处理这个问题的最佳方法是什么?我能想到的就是在表单上使用javascript代码提交来操作表单提交的URL.

小智 6

您可以向控制器添加以下条件:

if params[:utf8]
  redirect_to "/searches/#{params[:city_region]}/..."
end
Run Code Online (Sandbox Code Playgroud)


小智 1

您所需要的只是为此类页面创建一个路由。

如果您使用的是 Rails 3:

match '/search(/:city(/:property_type(/:min_square_footage(/:max_square_footage)))' => 'search#index', :as => :search
Run Code Online (Sandbox Code Playgroud)

(那些括号指的是一些可选变量)

然后你可以在你的视图中调用它,如下所示:

= link_to 'Search', search_url(:city_region => 'Vancouver', :property_type_id => 5, :min_square_footage => 0, :max_square_footage => 15000)
Run Code Online (Sandbox Code Playgroud)

  • 除非我不处理链接——页面呈现一个表单,用户填写该表单,提交该表单会生成 URL(该表单使用 GET 而不是 POST)。 (2认同)