RoR:View和Controller子目录?

时间:2009-12-11 19:48:45

标签: ruby-on-rails routing

我正在尝试在“锅炉盘”页面上使用这种技术(http://blog.hasmanythrough.com/2008/4/2/simple-pages),我希望将其保存在控制器视图文件夹的子目录中。

我该怎么做?以下似乎不起作用:返回“模板丢失”错误。

错误:

Missing template home/New_York_apartments.erb in view path app/views

/app
  /controllers
    home_controller.rb
    /old_pages
      home_controller.rb
  /views
    /home
      about.html.haml
      contact.html.haml
      index.html.haml
      /old_pages
        New_York_apartments.html.haml

routes.rb

map.namespace :old_pages do
  map.connect ':page', :controller => 'home', :action => 'show', :page => HomeController::PAGES 
end
map.home ':page', :controller => 'home', :action => 'show', :page => HomeController::PAGES 

controllers/home_controller.rb

class HomeController < ApplicationController

  # boiler-plate pages
  PAGES = ['about','contact'] 

  def index
    # homepage
  end

  def show
    render :action => params[:page] # passed in our routes
  end

end

controllers/old_pages/home_controller.rb

class OldPages::HomeController < ApplicationController

  # boiler-plate pages
  PAGES = [
    'New_York_apartments' # apprently something to do with new york apartments; who knows
  ]

  def show
    render :action => params[:page] # passed in our routes
  end

end

2 个答案:

答案 0 :(得分:0)

好的,找到了解决方案。我为一个更清晰的控制器目录和路由文件交换了一个稍微膨胀的主home_controller.rb,考虑到这些页面最终将被删除(子目录中的那些),我认为这是一个公平的妥协。

以下转载的编辑文件:


/app
  /controllers
    home_controller.rb
  /views
    /home
      about.html.haml
      contact.html.haml
      index.html.haml
      /old_pages
        New_York_apartments.html.haml

<强> routes.rb:

  # custom routes
  map.root :controller => 'home', :action => 'index' # root page
  map.home ':page', :controller => 'home', :action => 'show', :page => HomeController::PAGES # boiler-plate pages
  map.connect ':page.html', :controller => 'home', :action => 'show_old_pages', :page => HomeController::OLD_PAGES  # old static pages; only here to make the transition

<强> controllers/home_controller.rb:

class HomeController < ApplicationController

  def index
    # homepage
  end

  def show
    render :action => params[:page] # passed in our routes
  end

  def show_old_pages
    render :action => "old_pages/#{params[:page]}"
  end

  #### boiler-plate pages ####

  PAGES = [
    'about',
    'contact'
  ]

  OLD_PAGES = [
    'New_York_apartments' # apprently something to do with new york apartments; who knows
  ]

end

答案 1 :(得分:0)

以下是问题的根源:

map.namespace :old_pages do
  map.connect ':page', :controller => 'home', :action => 'show', :page => HomeController::PAGES 
end

这告诉Rails将oldpages/加到需要查找的任何路径前面。控制器将位于app/controllers/old_pages/home_controller并回复以/old_pages/home开头的网址。并期望观点位于app/views/old_pages/home/。您的目录布局将视图放在app/views/old_pages/home

无论你如何选择解决这个问题,你都会移动文件,并可能编辑其他文件。

最少努力解决方案:将当前app/views/home/old_pages目录重命名为app/views/old_pages/home。如果您要迁移整个网站,并希望保留当前版本的顽固用户,这是最好的方法。