Rails 'Map.Resources ()에서 기본 식별자 Param“ID”의 이름을 바꾸는 방법?
-
03-07-2019 - |
문제
나는 Rail 's에 의해 생성 된 모든 기본 경로를 좋아합니다. Map.Resources. 그러나 내 경로에서 숫자가 아닌 식별자를 사용하고 싶은 경우가 있습니다. 예를 들어, 중첩 경로가 사용자와 기사로 구성된 경우 표준 경로가 다음과 같이 작성 될 수 있습니다.
map.resources :users, :has_many => [:articles] # => e.g. '/users/:id/articles/:id'
그러나 레일에 의해 생성 된 기본 숫자 식별자를 사용하지 않는 많은 장점 / 이유가 있습니다. 모든 표준 조치에 대한 사용자 정의 경로를 작성하지 않고 기본값을 대체 할 수있는 방법이 있습니까? 다음 형식의 경로를 원한다고 말하십시오.
'/users/:login/articles/:id'
이런 종류의 경로는 달성 할 수 있습니다 Map.Resources?
해결책
Rails 2.3에서 매개 변수 이름을 변경할 수는 없으며 여전히 자동 라우팅을 사용합니다. #resources
제공.
해결 방법으로 매핑 할 수 있습니다 articles
a :path_prefix
그리고 :name_prefix
:
map.resources :articles, :path_prefix => "/users/:login",
:name_prefix => "user_"
그만큼 :path_prefix
URL에 영향을 미칩니다 :name_prefix
생성 된 명명 된 경로에 영향을 미치 므로이 경로로 끝납니다.
user_articles GET /users/:login/articles(.:format) {:controller=>"articles", :action=>"index"}
POST /users/:login/articles(.:format) {:controller=>"articles", :action=>"create"}
new_user_article GET /users/:login/articles/new(.:format) {:controller=>"articles", :action=>"new"}
edit_user_article GET /users/:login/articles/:id/edit(.:format) {:controller=>"articles", :action=>"edit"}
user_article GET /users/:login/articles/:id(.:format) {:controller=>"articles", :action=>"show"}
PUT /users/:login/articles/:id(.:format) {:controller=>"articles", :action=>"update"}
DELETE /users/:login/articles/:id(.:format) {:controller=>"articles", :action=>"destroy"}
그러나 일반적인 규칙으로서, 나는 Rails 기본 규칙을 고수합니다. :user_id
, 당신이 당신의 질문에 게시 한 라우팅으로. 일반적으로 이해됩니다 :id
그리고 :user_id
반드시 "숫자 식별자"를 암시하는 것은 아닙니다. 이들은 "리소스 식별자"를 암시합니다. 또한 기본 컨벤션을 고수함으로써 코드는 레일에서 자원 경로를 사용한 사람이라면 누구나 이해하기가 더 쉬울 것입니다.
리소스에 수치가 아닌 식별자를 사용하려면 재정의 #to_param
당신의 모델에서. 그런 다음 컨트롤러 에서이 식별자 (숫자 ID가 아닌)에서 찾을 수있는 파인더를 사용해야합니다. User#find_by_login!
.
다른 팁
모델에서 TO_PARAM을 재정의하여 URL에서 ID를 사용하는 기본값을 변경할 수 있습니다. 예를 들어
class User < ActiveRecord::Base
def to_param
login
end
end
user_articles_path(@user) => "/users/:login/articles"
당신이 만들어야 할 유일한 변경 사항은 컨트롤러의 ID가 아닌 로그인하여 사용자를 찾는 것입니다.