Rails路由:将root定义为命名空间

时间:2012-10-12 11:23:56

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

我有两个控制器:

app/
   /controllers
      posts_controllers.rb
      /mobile
         posts_controllers.rb

和我的routes.rb看起来像这样:

root :to => "posts#index"
resources :posts

namespace :mobile do
   root :to => "posts#index"
   resources :posts
end

但是当我访问/mobile时,无论如何渲染第一个控制器的索引页面,也尝试了这个:

namespace :mobile do
   root :to => "mobile/posts#index"
   resources :posts
end

但它给了我错误:uninitialized constant Mobile::Mobile 我想渲染第二个控制器的索引页面,我该怎么做?

修改

输入/ mobile我想渲染位于此处的文件:

app/
   views/
       /mobile
          /posts
             index.html.erb

但是这里有文件:

app/
   views/
       /posts
          index.html.erb

2 个答案:

答案 0 :(得分:18)

namespace :mobile do
   root :to => "posts#index"
   resources :posts
end

root :to => "posts#index"
resources :posts

而不是

root :to => "posts#index"
resources :posts

namespace :mobile do
   root :to => "posts#index"
   resources :posts
end

答案 1 :(得分:8)

namespace :mobile do
   get "/" => "posts#index"
   resources :posts
end

使用命名空间已经将 mobile 添加到该块内的控制器名称。