我在路线中有以下行:
match 'area/:area_id/stores', :to => "stores_directory#index", :as => "stores_directory"
我有一个表格,我可以在其中选择一个area_id为:
<%= form_tag stores_directory_path, :method=>:get do %>
<select id="area_id" name="area_id">
....
</select>
这会将area_id作为 ?. 所以,我的问题是:我将如何在区域和商店之间添加它?
我看到一个解决方案(也许不是最好的,但也完全可以接受(。可以编写自己的中间件来处理此请求,但我认为这是错误的方式(在这种情况下(。
相反,请使用 JS 重定向
这可以写成一个方法(使用JQuery的示例(:
$('#area_id option').click(function() {
if (this.value) { // check value is not empty
document.location.href = Routes.stores_directory_path({area_id: this.value})
}
});
或使用options_for_select:
options = []
areas.each do |a|
options << [a.to_s, a.id, {:onclick => "document.location.href = Routes.stores_directory_path({area_id: #{a.id}})"}]
end
options_for_select(options)
在这里,我使用了js-routes gem作为漂亮的url。
希望这会有所帮助。