Rails 仪表板命名空间的路由帮助

Rails Routing Help for Dashboard Namespace

我想我已经正确设置了所有内容,但是当我尝试访问 dashboards_posts_path 时,它会指向 dashboard_path 视图,而不是 app>views>dashboards>posts#index 视图。我不明白为什么。

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

您的问题是您在所有 namespace :dashboards 内容之前定义了 resources :dashboard(我推测)。请记住,路由从上到下解析。因此,路由将 GET dashboards/posts 解析为 dashboards/:id,这就是为什么您使用 posts.

id 路由到 DashboardsController#show 的原因

你为什么不试试:

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

哪个应该正确解析。

或者,将 resources :dashboards 放在 你的命名空间之后,像这样:

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

resources :dashboards