尝试在配置文件页面上显示用户信息时出现NoMethodError

时间:2012-06-03 19:20:58

标签: ruby-on-rails devise profile nomethoderror

我正在尝试使用带有设计的注册/登录系统制作一个简单的个人资料页面。我可以注册,登录和重定向到个人资料页面没问题,但是,当我尝试将与用户相关的变量插入到他们的个人资料页面时,我一直遇到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'

1 个答案:

答案 0 :(得分:1)

我很确定它应该是:

@user = User.find(params[:id])