CrazyCoderMonkey
CrazyCoderMonkey

Reputation: 433

NoMethodError if user types in random URL

When ever a user types in any random string in the websites url ie localhost:3000/rfgfgh or localhost:3000/gfgfgf/fhh it throws this random error.

I understand why it throws this error since I am checking if the user is contracter in the views and if they are display specific contracter code. I'm also using slugs to display contracter specific content. If the user goes to localhost:3000/contracter it checks for the slug contracter and then renders the page.

What are some solutions to remove this error? Is it possible to just redirect the user to the home page?

NoMethodError in Users#show

undefined method `contractor?' for nil:NilClass

1: <% if @user.contractor? %>
2:  <% title "#{@user.name}" %>

Upvotes: 0

Views: 93

Answers (1)

ronalchn
ronalchn

Reputation: 12335

Based on the error you see, it means that you are calling something like @myuser.contracter?, where @myuser is nil.

If the user isn't in the database, it will not find the user, and put nil in the @myuser object.

To redirect a user to the home page, simply check if the variable is nil in the controller, and redirect if necessary, eg:

@myuser = User.find(params[:id]) # or params[:username]
if @myuser.nil? # check if nil
  redirect_to root_url, :notice => "User does not exist!" # redirect to home page
end

Upvotes: 2

Related Questions