Rails 3.1.1 で新しい Rails アプリを作成しましたが、アプリケーションのレイアウトがブラウザーにレンダリングされません。レンダリングされるのは、ビューに配置したコードだけです (例: views/public/home.html.erb)。
<%= yield %> を通じてパイプされるものだけをレンダリングします。たとえば、localhost:3000/public/home は、次のように表示されるだけです。
<h1>Homepage</h1>
<h2>Here we go.</h2>
<a href="/#">Visit the login page</a>
/layouts/application.html.erb の内容は次のとおりです。
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<ul class="user_nav">
<% if current_user %>
<li>
Logged in as <%= current_user.email %>.
</li>
<li>
<%= link_to "Log out", logout_path %>
</li>
<% else %>
<li>
<%= link_to "Sign up", signup_path %>
</li>
<li>
<%= link_to "Log in", login_path %>
</li>
<% end %>
</ul>
<% flash.each do |name, msg| %>
<%= content_tag :div, msg, :id => "flash#{name}" %>
<% end %>
<%= yield %>
<h1>test!</h1>
</body>
</html>
私のルートは次のとおりです:
root :to => "public#home"
match "/secret" => "public#secret"
get "logout" => "sessions#destroy", :as => "logout"
get "login" => "sessions#new", :as => "login"
get "signup" => "users#new", :as => "signup"
resources :users
resources :sessions
application_contoller.rb の内容は次のとおりです。
class ApplicationController < ActionController::Base
protect_from_forgery
end
public_controller.rb の内容は次のとおりです。
class PublicController < ActionController::Base
protect_from_forgery
def home
end
def secret
end
end
sessions_contoller.rb の内容は次のとおりです。
class SessionsController < ApplicationController
def new
end
def create
user = login(params[:email], params[:password], params[:remember_me])
if user
redirect_back_or_to root_path, :notice => "Logged in!"
else
flash.now.alert = "Email or password was invalid"
render :new
end
end
def destroy
logout
redirect_to root_path, :notice => "Logged out"
end
end
users_controller.rb の内容は次のとおりです。
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to root_path, :notice => "Signed up!"
else
render :new
end
end
end
ベストアンサー1
私自身もちょうど同じ問題に遭遇しましたが、問題は単なる単純な間違いでした。
コントローラー PublicController は "ActionController::Base" をサブクラス化しています。ApplicationController 以外のコントローラーは、そのビューが application.html.erb レイアウト内でレンダリングされるように、ApplicationController からサブクラス化する必要があります。
変更する場合
PublicController < ActionController::Base
に
PublicController < ApplicationController
動作するはずです。