简体   繁体   中英

How can I write Rails routes to identify particular parameter

I have a route like the following.

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

What I need is after :city, it can be filter1, filter2 etc.. Else

filter1/filter2 together.

So I need routes like

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

But the problem here is when I am sending filter2 or filter3 only then it is taken as filter1.

Is there any way to achieve this ?

It is difficult problem n-depth filter.

I recommend you like this

in 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

in 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

additional comment.

in routes.rb

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

in shop_controller.rb

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM