dimanche 12 février 2017

Best practice in Rails 3: namespaced controller and routes with module set

I quite often use following approach, but it has one flaw - I have to add module to all my nested routes... Here is an example:

I want to create following structure:

/posts_controller.rb
/posts/comments_controller.rb
/posts/follow_ups_controller.rb
/posts/likes_controller.rb

So 1 main controller and multiple "child" controllers with scoped entities (comments, follow-ups and likes belong to 1 post).

This structure makes it really easy to handle big applications and I'm quite satisfied with it, but here is the problem:

Rails itself doesn't put the nested routes into the posts namespace:

resources :posts do
  resources :comments
  resources :follow_ups
  resources :likes
end

# leads to following controllers & views (which are not namespaced):

posts_controller.rb
likes_controller.rb
follow_ups_controller.rb
likes_controller.rb

So my solution is to add the module name to each subroute, which is not very dry, but the only way to make it work:

resources :posts do
  resources :comments, module: "posts"
  resources :follow_ups, module: "posts"
  resources :likes, module: "posts"
end

Does anyone have a suggestion to improve this? We also talk about Rails 3 here and I don't need route concerns, since the subroutes are quite individual..

Thanks!

Aucun commentaire:

Enregistrer un commentaire