工夫で登録・ログインシステムを使って簡単なプロフィールページを作ろうとしています。登録、ログイン、プロファイル ページへのリダイレクトは問題ありませんが、ユーザーに関連する変数をプロファイル ページに挿入しようとすると、NoMethodError が発生し続けます。各プロファイル ページには特定のユーザー情報を表示する必要があるため、情報を表示するために current_user を使用したくありません。これに対する解決策をどこでも探しましたが、なぜこれが機能しないのかわかりません。すべてのコードは次のとおりです。
index.html.erb
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
<div id="user_nav">
<% if user_signed_in? %>
Signed in as <%= current_user.email %>. Not you?
<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> or <%= link_to "sign in", new_user_session_path %>
<% end %>
</div>
show.html.erb
<%= @user.firstname %>
You are signed in
ユーザーコントローラー
class UsersController < ApplicationController
def show
@user = User.find_by_username(params[:id])
end
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :firstname, :lastname
end
route.rb
Test1::Application.routes.draw do
devise_for :users
resources :user
authenticated :user do
root :to => 'users#show'
end
root :to => 'home#index'
end
エラーメッセージ
NoMethodError in Users#show
Showing /Documents/Aptana Studio 3 Workspace/test1/app/views/users/show.html.erb where line #1 raised:
undefined method `firstname' for nil:NilClass
Extracted source (around line #1):
1: <%= @user.firstname %>
2: You are signed in
Rails.root: /Documents/Aptana Studio 3 Workspace/test1
Application Trace | Framework Trace | Full Trace
app/views/users/show.html.erb:1:in `_app_views_users_show_html_erb___52288684_2184635920'