HandDisco
HandDisco

Reputation: 627

"NoMethodError in Users#show" Hartl Chapter 7

NoMethodError in Users#show

Error: undefined method `name' for nil:NilClass

I've been following Hartl's rails tutorials for Rails 4.0 and I've been stuck on this for a couple of days now. The error highlights line 1 as the problem in the 'show.html.erb file'. Also, ruby's 'private' keyword doesn't work so i've hashed it out in 'users_controller.rb' which stops anymore errors. I'd be very, very grateful for any help. Thanks.

app/views/show.html.erb

<% provide(:title, @user.name) %>
<div class="row">
  <aside class="span4">
    <section>
      <h1>
        <%= gravatar_for @user %>
        <%= @user.name %>
      </h1>
    </section>
  </aside>
</div>

users_controller.rb

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

  def new
    @user = User.new

        def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  #private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end
end
end

Upvotes: 0

Views: 506

Answers (2)

user2503775
user2503775

Reputation: 4367

you have two problems in your code:

first : you have two functions named new, the first one should be show.

second : you missed end in the end of the second function (move it from the controller's ending)

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51161

You probably didn't set @user instance variable. You should have in your controller:

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

Upvotes: 1

Related Questions