【问题标题】:How can I write Rails routes to identify particular parameter如何编写 Rails 路由来识别特定参数
【发布时间】:2013-12-03 12:41:18
【问题描述】:

我有如下路线。

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

我需要的是:city之后,可以是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。

有什么办法可以做到吗?

【问题讨论】:

  • 它将始终按顺序进行(/:filter1)(/:filter2)(/:filter3/)(:filter4)。最好在filter 上实现,例如match "/shop/filter/:city" => "shop#filter", :method => :post, :as => :shop_filter,这样它就可以通过参数作为/shop/filter/:city?filter1=value1&filter2=value2&filter3=value3&filter4=value4 接受任意数量的过滤器
  • 谢谢阿米特。但我真的不想使用?filter1value1&filter2=value2&filter3=value3&filter4=value4。数据将在 url 斜杠之间。有没有办法做到这一点?
  • "/shop/:city/:filter1/:filter3" => "shop#filter" 表示如果你只想要filter1filter3 而不是filter2,那么这是不可能的,因为参数总是按顺序排列的。这些不同的过滤器有什么区别?
  • 它来自不同的类别。有时某些类别将不存在。像电子零件,电子零件项目等。所以我需要像 City/TV/Tv-Stand 这样的 url。如果用户只需要支架,我需要它,例如 City/Tv-Stand,如果他只需要电视,则需要 City/TV。如果他需要两者,那么 City/Tv/Tv-Stand。在这里我无法理解,用户正在请求 TV 或 TV Stand 或两者。无论如何,在rails中它是否按顺序排列?像 filter1 或 filter2 或 filter3 ?
  • 不,这条路线的问题是,即使您说City/Tv-Stand,它也会将Tv-Stand 作为过滤器1(正如您所期望的过滤器2)。我希望你明白我的意思?

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


【解决方案1】:

n-depth filter是个难题。

我推荐你喜欢这个

在 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

【讨论】:

  • 感谢您的回答。但我不能使用重定向。过滤器来自不同的类别。有时某些类别将不存在。像电子零件,电子零件项目等。所以我需要像 City/TV/Tv-Stand 这样的 url。如果用户只需要支架,我需要它,例如 City/Tv-Stand,如果他只需要电视,则需要 City/TV。如果他需要两者,那么 City/Tv/Tv-Stand。在这里我无法理解,用户正在请求 TV 或 TV Stand 或两者。无论如何,在rails中它是否按顺序排列?像 filter1 或 filter2 或 filter3 ?
  • 添加了额外的 cmets。它涵盖了任何深度过滤器。祝你好运
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多