2012-10-25 2 views
4

다음과 같은 경로를 설정하려고합니다 : 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 (으)로 리디렉션됩니다.

+0

방금'자원을 사용하지 않는 특별한 이유가 있나요 레이크 : posts' 및 쿼리 문자열에 필터 params를 보냅니 까? (예 :'acme.com/posts? category = foo & status = bar') – rthbound

+0

'/ posts/: category/: status /'또는 적어도/posts/category/: 카테고리/status/: status' – Mohamad

답변

1

config/routes.rb에있는 더 RESTful resources :posts을 사용하고 쿼리 문자열에 매개 변수를 보낼 수 있습니다.

이 방법을 사용하면 모든 매개 변수가 선택 사항이며 미리 정의 된 매개 변수를 사용하는 데만 국한되지 않습니다.

+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 

적어도 도움이 되길 바랍니다.

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

이와 당신이 당신의 자신의 필터 경로를 구축 할 수 있습니다 :

+0

그러면 경로가 없습니다. {: controller => "posts", : status => nil, : format => : under_consideration}'오류가 발생합니다. .. 형식이 어떻게 거기에 들어 왔는지 확실하지 않은 것은 상태가되어야합니다 ... 반전, 원래는 그렇게했기 때문에 하단 경로 일치 카테고리가 비슷한 오류를 발생시킵니다! – Mohamad

0

당신이 뭔가를 시도 할 수 있습니다. 그런 다음 컨트롤러에서 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 
관련 문제