2012-10-25 67 views
4

我試圖設置一個如下所示的路由:acme.com/posts/:category/:status:category:status都是可選的。我寫了許多變化,但沒有工作:Rails中可選參數的路由

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

+0

你有什麼不想只使用'資源特殊的原因:posts'並在查詢字符串中發送過濾參數? (例如,'acme.com/posts?category = foo&status = bar') – rthbound

+0

我想要漂亮的URL,所以它出現'/ posts /:category /:status /'或至少'/ posts/category /:category/status /:status' – Mohamad

回答

1

您可以使用更多RESTful resources :posts(在config/routes.rb中)並在查詢字符串中發送參數。

使用該方法,所有參數都是可選的,並且不限於使用預定義的參數。

+1

我認爲我會這麼做,因爲這樣做比事實證明要麻煩得多,但是最好能有'/ posts /:category /:status /或者至少/ posts/category /:category/status /:status'而不是查詢參數... – Mohamad

0

這是否適合您?

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

希望至少有幫助!

+0

這會引發一個錯誤'無路由匹配{:controller =>「posts」,:status => nil,:format =>:under_consideration}'。 ..不知道格式是如何爬行在那裏,這應該是狀態...顛倒,這是我原來做的,所以底部路線匹配類別引發了類似的錯誤! – Mohamad

0

你可以嘗試這樣的事:

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

有了這個,你可以建立自己的過濾器的路徑。然後你可以在你的控制器中解析params[:category_or_status]並獲得給定的類別或狀態。

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 =管理員/職位耙路線

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