Rails 中带有可选参数的路由

Moh*_*mad 6 routes ruby-on-rails ruby-on-rails-3

我正在尝试设置一条如下所示的路线:acme.com/posts/:category/:status。和:category都是:status可选的。我写了很多变体,但没有一个起作用:

resources :posts do
  match '(/:category)(/:status)', to: 'posts#index', as: 'filter', on: :collection
end

# Category Links
link_to "Questions", filter_posts_path(:questions)
link_to "Suggestions", filter_posts_path(:suggestions)

# Status Links
link_to "Published", filter_posts_path(params[:category], :published)
link_to "Draft", filter_posts_path(params[:category], :draft)
Run Code Online (Sandbox Code Playgroud)

这个想法是能够1) 按类别过滤2) 按状态过滤以及 3) 按类别和状态过滤(如果两者都可用)。当前的设置也打破了我的/posts/new道路,总是重定向到posts#index.

rth*_*und 1

您可以使用更 RESTful resources :posts(在 config/routes.rb 中)并在查询字符串中发送参数。

通过这种方法,所有参数都是可选的,并且您不限于使用预定义的参数。