在Rails中使用可选参数的路由

时间:2012-10-25 19:04:44

标签: ruby-on-rails ruby-on-rails-3 routing

我正在尝试设置如下所示的路线: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)

这个想法是能够 1)按类别过滤 2)按状态过滤和3)按类别和状态过滤。当前设置还会破坏我的/posts/new路径,始终重定向到posts#index

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

我有这种变化,似乎工作正常:

  namespace :admin do
    resources :posts, :except => [:show] do
      collection do
        get "/(:category(/:status))", to: "posts#index", as: "list", :constraints => lambda{|req|
          req.env["PATH_INFO"].to_s !~ /new|\d/i
        }
      end
    end
  end

= CONTROLLER = admin / posts rake route

list_admin_posts GET    /admin/posts(/:category(/:status))(.:format)                 admin/posts#index

答案 2 :(得分:0)

这适合你吗?

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

希望至少它有所帮助!

答案 3 :(得分:0)

您可以尝试这样的事情:

match '/filter/*category_or_status' => 'posts#index', as: 'filter'

有了这个,你可以建立自己的过滤器路径。然后,您可以在控制器中解析params[:category_or_status]并获取类别或状态(如果已给出)。

相关问题