【问题标题】:Route a controller to namespace :admin to /admin将控制器路由到命名空间 :admin 到 /admin
【发布时间】:2012-02-20 06:04:06
【问题描述】:

我觉得这可能是一个愚蠢的问题,但已经晚了,我的头有点融化了。所以我很感谢你的帮助。

我正在尝试将 url http://localhost:3000/admin 映射到仪表板控制器,但我失败了。也许这甚至是不可能的或完全错误的想法,但无论如何我的路线看起来像这样,是的

namespace :admin do
  resources :dashboard, { :only => [:index], :path => '' }
  ...
end

还有我的简单dashboard_controller.rb

class Admin::DashboardController < ApplicationController
  before_filter :authenticate_user!
  filter_access_to :all

  def index
    @schools = School.all
  end
end

我的视图位于views/admin/dashboard/index.html.erb

感谢您的任何意见

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 routing


    【解决方案1】:

    如果您要做的只是将/admin 路由到该仪表板控制器,那么您通过这样的命名空间使其过于复杂。

    使用这样的嵌套资源命名空间意味着:index 操作将是/admin/dashboards,而不是拥有干净的/admin 路由(您可以通过在命令行运行rake routes 来验证这一点获取您的路线列表)。

    选项 1:您的意思是这样命名它

    # putting this matched route above the namespace will cause Rails to 
    # match it first since routes higher up in the routes.rb file are matched first
    match :admin, :to => 'admin/dashboards#index'
    namespace :admin do
      # put the rest of your namespaced resources here
      ...
    end
    

    选项 2:您并不是要这样命名它

    路线:

    match :admin, :to => 'dashboards#index'
    

    控制器:

    # Remove the namespace from the controller
    class DashboardController < ApplicationController
      ...
    end
    

    视图应移回:

    views/dashboards/index.html.erb
    

    更多信息:http://guides.rubyonrails.org/routing.html

    【讨论】:

    • 感谢抢劫!选项 1 修复了我。
    • 这些仅适用于将特定路径 /admin 映射到特定操作仪表板#index。它们也不会将 /admin/:action 映射到仪表板#:action。
    【解决方案2】:

    关于http://guides.rubyonrails.org/routing.html我更喜欢这个

    namespace :admin do
      root to: "admin/dashboards#index"
      resources :dashboard
    end
    

    【讨论】:

      【解决方案3】:

      试试这个:

      namespace :admin do
          root to: 'users#index' # whatever. Just don't start with /admin
          #resources :dashboards <= REMOVE THIS LINE !
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-26
        • 2023-03-16
        • 2012-05-14
        • 1970-01-01
        • 2015-07-05
        • 1970-01-01
        相关资源
        最近更新 更多