[英]Routes with optional params in Rails
我正在嘗試設置如下所示的路由: acme.com/posts/:category/:status
: acme.com/posts/:category/:status
: 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
。
您可以使用更多的RESTful resources :posts
(在config / routes.rb中),並在查詢字符串中發送參數。
使用這種方法,所有參數都是可選的,並且您不僅限於使用預定義的參數。
我有這種變化,它似乎工作正常:
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 =管理員/發布耙路
list_admin_posts GET /admin/posts(/:category(/:status))(.:format) admin/posts#index
這對您有用嗎?
resources :posts do
collection do
match '/:category(/:status)', to: 'posts#index', as: 'filter'
match '/:status', to: 'posts#index', as: 'filter'
end
end
希望至少有幫助!
您可以嘗試這樣的事情:
match '/filter/*category_or_status' => 'posts#index', as: 'filter'
這樣,您可以構建自己的過濾器路徑。 然后,您可以在控制器中解析params[:category_or_status]
並獲取類別或狀態(如果已給出)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.