如何编写Rails路由以识别特定参数

时间:2013-12-03 12:41:19

标签: ruby-on-rails ruby ruby-on-rails-3.2 routes

我有一条如下路线。

match "/shop/:city(/:filter1)(/:filter2)(/:filter3/)(:filter4)"  =>  "shop#filter", :method => :post, :as => :shop_filter

我需要的是:城市,它可以是filter1,filter2等。否则

filter1 / filter2在一起。

所以我需要像

这样的路线
match "/shop/:city/:filter1" =>  "shop#filter", :method => :post, :as => :shop_filter

match "/shop/:city/:filter2" => "shop#filter", :method => :post, :as => :shop_filter


match "/shop/:city/:filter1/:filter2" =>  "shop#filter", :method => :post, :as => :shop_filter

match "/shop/:city/:filter1/:filter3"  =>  "shop#filter", :method => :post, :as => :shop_filter

但这里的问题是当我发送filter2或filter3时它才被当作filter1。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

难以解决问题n深度过滤。

我建议你喜欢这个

在routes.rb

match "/shop/:city/:filter" =>  "shop#one_depth_filter", :method => :post, :as => :shop_one_depth_filter
match "/shop/:city/:filter/:subfilter" =>  "shop#two_depth_filter", :method => :post, :as => :shop_two_depth_filter
shop_controller.rb中的

def one_depth_filter
    redirect_to root_path unless params[:filter] != 'filter1' && params[:filter] != 'filter2'
end

def two_depth_filter ... end # same logic like one_depth_filter

补充评论。

在routes.rb

match "/shop/:city/*filter" =>  "shop#filter", :method => :post, :as => :shop_filter
shop_controller.rb中的

def filter
    filters = params[:filter].split("/")
    # implement
end