티스토리 뷰
routes.rb 에서 nested 라우팅 관리를 하다보면 아래와 같은 경우가 종종 생긴다.
resources :messaged do
resources :comments
resources :categories
resources :tags
end
resources :posts do
resources :comments
resources :categories
resources :tags
end
resources :items do
resources :comments
resources :categories
resources :tags
end
comments, categories, tags 와 같은 똑같은 resources 가 중복되어 사용되는 경우 concern method를 이용하여 간단히 나타낼 수 있다.
concern :sociable do
resources :comments
resources :categories
resources :tags
end
resources :messages, concerns: :sociable
resources :posts, concerns: :sociable
resources :items, concerns: :sociable
특정 액션을 제한하고 싶으면 options 인자를 이용하면 된다.
concern :sociable do |options|
resources :comments, options
resources :categories, options
resources :tags, options
end
resources :messages, concerns: :sociable
resources :posts, concerns: :sociable
resources :items do
concerns: :sociable, only: :create
end
concern 정의를 파일에 별도로 뽑아 저장할 수 있다.
# app/concerns/sociable.rb
class Sociable
def self.call(mapper, options)
mapper.resources :comments, options
mapper.resources :categories, options
mapper.resources :tags, options
end
end
# config/routes.rb
concern :sociable, Sociable
resources :messages, concerns: :sociable
resources :posts, concerns: :sociable
resources :items do
concerns: :sociable, only: :create
end
'Ruby&Rails > Rails' 카테고리의 다른 글
| [Rails] 웹 API를 위한 JSON, XML 응답 (0) | 2015.07.07 |
|---|---|
| [Rails] Rails에서의 subdomain 설정하기 (0) | 2015.07.06 |
| [Rails] Ajax로 Create & Delete 기능 구현 (0) | 2015.06.26 |
| [Rails] N+1 쿼리 문제 해결방안 (0) | 2015.06.25 |
| [Rails] Redirect and Flash 문법 (0) | 2015.06.24 |
