application.html.erb仍未呈现

时间:2015-11-12 21:36:52

标签: ruby-on-rails ruby views

我生成了一个Rails应用程序,并正在玩内部。以前我的application.html.erb正在渲染,但现在似乎Rails完全无视它,因为它甚至不会产生错误。

Stack Overflow上有很多关于这个问题的问题。我看过我认为的全部内容,但没有人帮助过。

我的路线:

Rails.application.routes.draw do

  # static_pages from rails tutorial ch. 3
  get 'static_pages/home'
  get 'static_pages/help'
  get 'static_pages/about'

end

这是views / layout / application.html.erb

<!DOCTYPE html>
<html>
    <head>
        <title>This Title is not showing up</title>
        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
        <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
        <%= csrf_meta_tags %>
    </head>
    <body>
    <p> why isnt this showing up?? </p>
        <%= yield %>

    </body>
</html>

这是static_pages_controller:

class StaticPagesController < ApplicationController   
    layout 'application' #<- I know this shouldn't be necessary, but I thought i'd try

    def initialize
        @locals = {:page_title => 'Default'}
    end

    def about
        @locals[:page_title] = 'About'
        render @locals
    end

    def help
        @locals[:page_title] = 'Help'
        render @locals
    end

    def home
        @locals[:page_title] = 'Home'
        render @locals
    end

end

这是应用程序控制器:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

没有其他布局。我的Views文件夹具有以下结构:

-Views
 |-layouts
 ||-application.html.erb
 |
 |-static_pages
 ||-about.html.erb
 ||-home.html.erb
 ||-help.html.erb

我曾尝试在application.html.erb中故意生成错误,调用不存在的变量以及其他任何恶作剧。 Rails完全无视我,我感到不安全。

我想要做的就是在<title>中显示页面名称,但我甚至无法正确渲染纯文本。我怎样才能使这个工作,以便我可以正确地失败获得标题中的控制器变量?

1 个答案:

答案 0 :(得分:4)

您不应该覆盖控制器initialize方法。这样做会破坏基类行为。

虽然我相信,只是从super调用initialize将解决您的问题,正确的Rails方法初始化特定操作的控制器是使用before filter代替

示例:

class StaticPagesController < ApplicationController   
  layout 'application'

  before_action :load_locals

  def load_locals
    @locals = {:page_title => 'Default'}
  end

  ...
end