Railsで綺麗なURLにしたいと思うと一つのControllerに機能が集中して困ることがあります。
/comments
/posts/1/comments
/users/1/comments
# config/routes.rb:
Foo::Application.routes.draw do
resources :comments
resources :posts do
resources :comments
end
resources :users do
resources :comments
end
end
例えばこんな風にしたい時。
# app/controllers/comments_controller.rb:
class CommentsController < ApplicationController
def index
@comments =
if params[:post_id]
Post.find(params[:post_id]).comments
elsif params[:user_id]
User.find(params[:user_id]).comments
else
Comment.all
end
end
end
こんな風に書く?えーキモーイ。そもそもそれぞれの場合でviewが全然違うんですけどーみたいな場合。
そんなんねぇ俺の糞みたいな悩みはねぇStack Overflowさんに聞けば一発なんですよ。
Rails Namespace vs. Nested Resource - Stack Overflow
controllerのnamespaceでスッキリ書けるみたいです。
/comments
/posts/1/comments
/users/1/comments
# config/routes.rb:
Foo::Application.routes.draw do
resources :comments
resources :posts do
resources :comments, controller: 'posts/comments'
end
resources :users do
resources :comments, controller: 'users/comments'
end
end
# app/controllers/comments_controller.rb:
class CommentsController < ApplicationController
def index
@comments = Comment.all
end
end
# app/controllers/posts/comments_controller.rb:
class Posts::CommentsController < ApplicationController
def index
@comments = Post.find(params[:post_id]).comments
end
end
# app/controllers/users/comments_controller.rb:
class Users::CommentsController < ApplicationController
def index
@comments = User.find(params[:user_id]).comments
end
end
$ rake routes
(snip)
comments GET /comments(.:format) comments#inde
post_comments GET /posts/:post_id/comments(.:format) posts/comments#index
user_comments GET /users/:user_id/comments(.:format) users/comments#index
(snip)
おおお、これはスッキリ!
Stack Overflow脳の恐怖。