如何为两个名称空间创建路由

时间:2015-10-01 05:53:49

标签: ruby-on-rails namespaces

我正在尝试将我的rails项目拆分为常规用户的前端和管理员的后端。因此我创建了一个命名空间'admin',以便我可以轻松控制admin。创建管理命名空间后,我改变了路由

Rails.application.routes.draw do
 authenticated :user do
    root to: 'dashboard#index', as: :authenticated_root
  end

  unauthenticated do
    root to: "home#index"
  end

  match '(errors)/:status', to: 'errors#show', constraints: { status: /\d{3}/ }, via: :all

  devise_for :users, skip: [:registrations]
  as :user do
    get 'my/profile/edit' => 'devise/registrations#edit', as: 'edit_user_registration'
    patch 'my/profile' => 'devise/registrations#update', as: 'user_registration'
  end

  resources :users

  resources :events do
    patch :archive, :unarchive
  end
end

到这个

Rails.application.routes.draw do
  namespace :admin do
    authenticated :user do
      root to: 'dashboard#index', as: :authenticated_root
    end

    unauthenticated do
      root to: "home#index"
    end

    match '(errors)/:status', to: 'errors#show', constraints: { status: /\d{3}/ }, via: :all

    devise_for :users, skip: [:registrations]
    as :user do
      get 'my/profile/edit' => 'devise/registrations#edit', as: 'edit_user_registration'
      patch 'my/profile' => 'devise/registrations#update', as: 'user_registration'
    end

    resources :users

    resources :events do
      patch :archive, :unarchive
    end
  end
end

经过这些改变,我得到了这个页面

Rails::WelcomeController#index as HTML

有谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

如果我理解你的要求,你想把管理命名空间中的所有内容都放在管理命名空间中,但将所有内容(例如根页面)留在外面。

但是在您的路由示例中,您将所有内容放在admin命名空间中,甚至是根页面。

一般来说,你想要的东西是:

Rails.application.routes.draw do
  namespace :admin do
    # put admin stuff here
  end

  # put everything NOT in the admin interface outside your namespace
  # you want a root route here. That's the page that'll be displayed by default      
  root to :your_root_stuff

  # and if you have users who aren't admins, devise and authenticated routes too
  # ... other stuff
end