레일 : link_to에 값이없는 매개 변수를 지정합니다
-
08-07-2019 - |
문제
경로를 가정합니다
map.resources :articles
어떻게 얻습니까?
/articles?most_popular
사용 link_to
방법?
다음을 시도했습니다.
link_to articles_path(:most_popular) # exception
link_to articles_path(:most_popular => nil) # /articles
link_to articles_path(:most_popular => true) # /articles?most_popular=true
참고 : 사용 중입니다 inherited_resources ~와 함께 has_scope
해결책
매개 변수에 값을 추가하지 않으면 W3C 표준을 존중하지 않으며, 이는 매개 변수 섹션에 양식이 있어야합니다. field=value
.
대신 기사 컨트롤러에 새로운 : most_popular action을 추가하는 것이 좋습니다.
당신의 경로에서 .rb :
map.resources :articles, :collection => {:most_popular=>:get}
컨트롤러에서 :
class ArticlesController < ApplicationController
...
def most_popular
@articles = ...
end
당신의 견해에 :
link_to most_popular_articles_path() # /articles/most_popular
이것은 HTML 호환이되며 URL은 실질적으로 동일하게 보이며 (하나의 /하나 /) 컨트롤러가 단순화됩니다 (당신은 인덱스와 가장 많이 _popular 동작이 분리 될 것입니다).
문안 인사!
업데이트 (2017): W3C 표준은 field=value
구문 (또는 더 이상 명령하지 않음). 그러나 일부 서버는이 구문을 준수하지 않는 쿼리에서 "초크"로 문서화됩니다. 보다 값이없는 경우 URL 쿼리 매개 변수가 유효합니까? 자세한 내용은.
다른 팁
마지막 예제 :
link_to articles_path(:most_popular => true) # /articles?most_popular=true
올바른 방법입니다. 그렇지 않으면 손으로 링크를 구성 할 수 있습니다.
<a href="<%= articles_path %>?most_popular">articles</a>
제휴하지 않습니다 StackOverflow