Question

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).

Was it helpful?

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

OTHER TIPS

I'm a fan of explicitly naming all routes for security and clarity on what routes are out there. So for your case doing something like:

#Dashboard
get '/dashboard', to: 'dashboard#user', as: 'dashboard'
get '/dashboard/posts/:id', to: 'posts#show', as: 'post'

#Posts
get '/dashboard/posts/:id', to: 'posts#new', as: 'new_post'
post '/dashboard/posts/:id', to: 'posts#create', as: 'create_post'
put '/dashboard/posts/:id', to: 'posts#update', as: 'create_post'

More info at http://guides.rubyonrails.org/routing.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top