Reputation: 353
Am following Michael Hartl's tutorial and one problem I was having was I kept getting this error undefined method 'name' for nil:NilClass
for my show page view where I have:
<% provide(:title, @user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>
<%= gravatar_for @user %>
<%= @user.name %>
</h1>
</section>
</aside>
</div>
Now in my User Controller I had the show method under the create and new method when I was getting this error:
class UsersController < ApplicationController
def new
@user = User.new
end
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
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
So then when I removed the show method from and put it above the create method I stopped getting the error. So does rails call methods in some order? just need help understanding why.
Show method moved above create:
class UsersController < ApplicationController
def new
@user = User.new
end
def show
@user = User.find(params[:id])
end
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
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
Upvotes: 0
Views: 225
Reputation: 6834
The problem is that you have an extra end
command floating in the middle of your controller:
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
end # This end doesn't belong here
This is causing Rails to think that it has reached the end of your controller code before it really has and this is why you are seeing different behavior based on whether you place the show
method before or after this extra end
. When your show
method was above this it was included in the controller. When your show
method was below this it was not included in the controller.
You will want your controller to look like this:
class UsersController < ApplicationController
def new
@user = User.new
end
def show
@user = User.find(params[:id])
end
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 # This end statement closes the UsersController class
Then the order of your methods won't matter.
Also, in the future, please include the information about the line of code that is printed next to the error message. This will make it easier to help debug the problem.
Upvotes: 1