0

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

显示.html.erb

<%= @user.firstname %>
You are signed in

用户控制器

class UsersController < ApplicationController
  def show
    @user = User.find_by_username(params[:id])
  end
end

用户.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

路由.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'
4

1 回答 1

1

我很确定它应该是:

@user = User.find(params[:id])
于 2012-06-03T19:40:15.370 回答