Search code examples
ruby-on-railscontrollerroutesadmindashboard

Rails Routing Help for Dashboard Namespace


I think I have everything set up correctly, but when I try to visit the dashboards_posts_path it directs to the dashboard_path view instead of app>views>dashboards>posts#index view. I'm not understanding why.

router

namespace :dashboards do
 resources :posts
 resources :tags
 resources :ingredients
 resources :comments
 resources :pages
 resources :users
end

controller

class Dashboards::PostsController < DashboardsController
 # before_action :admin_authorize, only: [:new, :create, :edit, :update, :destroy]
 protect_from_forgery with: :null_session
 layout "dashboards"

 def current_user
  if session[:user_id]
   @current_user = User.find(session[:user_id])
  end
 end

 def index
  @posts = Post.newest.paginate(page: params[:page], per_page: 3)
  @all_posts = Post.all
 end
end

views

routes

log


Solution

  • Your problem is that your defined resources :dashboard before all your namespace :dashboards stuff (I'm speculating). Remember, routes resolve top to bottom. So, routing resolves GET dashboards/posts to dashboards/:id which is why you're routing to DashboardsController#show with and id of posts.

    Why don't you try:

    resources :dashboards do
      resources :posts
      resources :tags
      resources :ingredients
      resources :comments
      resources :pages
      resources :users
    end
    

    Which should resolve correctly.

    Alternatively, put resources :dashboards after your namespace stuff, like this:

    namespace :dashboards do
      resources :posts
      resources :tags
      resources :ingredients
      resources :comments
      resources :pages
      resources :users
    end
    
    resources :dashboards