Search code examples
ruby-on-railsruby-on-rails-4nested-resources

Proper routing for User model dashboard and his posts in Rails 4.0


My question here is about the proper way to do the routing and controllers for my simple app. Honestly I got stuck with the User model and Post model.

I've got it routed like this:

match '/dashboard', to: 'dashboard#user'

In the controller it takes the session uid to find the user and his posts (the posts and user profile are completely private to the user). So far dashboard serves its purpose. The question is where do I go from here? Posts are shown in the same view as the posts list. For the editing/updating and creating I would like my routes to be /dashboard/posts/:id.

This would point me to using a resource. Finally: Is using scope '/dashboard' or path: '/dashboard/posts' a good approach, or is it against "the Rails Way"? Or do I have a completely wrong idea what's going on here?

I'm afraid of completely messing up the code and repeating myself over and over again (as in authentification, and keeping the routes clean).


Solution

  • You could either use a namespace or nested resources, like this:


    Namespace

    #config/routes.rb
    namespace :dashboard do
      root to: "users#index"
      resources :posts, :comments
    end
    
    #app/controllers/dashboard/users_controller.rb
    Class UsersController < Dashboard::ApplicationController.rb
    end
    

    Nested

    #config/routes.rb
    resources :user, path: "dashboard", as: "dashboard" do
      resources :ads
    end