views:

35

answers:

1

Guys and girls,

I have been working on this problem for a while but still no joy. This is my second question within this general area, because the last question was getting too long and this is now more well-defined.

Summary of the Problem:

I am loading a page for my customers and I get error:

undefined method 'name' for Nil:NilClass

My Code

#Link on views/users/show.html.erb:
<%= link_to "Customer Account", :action => "home", :controller => "customers", :id => @user.user_type_id %>

#Regular Route:
map.connect 'customers/home/:id', :controller => 'customers', :action => 'home'

#Rake Routes, first entry:
/customers/home/:id  :controller=>:"customers", :action=>"home"

#Customers Controller:
def home
  render :layout => 'home'
  @customer = Customer.find(params[:id])
  @user = @current_user_session.user
  flash[:error] = "Customer not found" and return unless @customer
  @jobs = @customer.jobs
end

#views/customers/home.html.erb:
<%= @customer.name %>

I have absolutely no idea why this seemingly clear sequence of events is resulting in a NilClass. Search the console for Customer.find(2) returns the correct customer. What is this noob missing? Thank you very much.

+3  A: 

You are rendering the view before you set @customer, so it is nil. Try the following:

def home
  @customer = Customer.find(params[:id])
  @user = @current_user_session.user
  flash[:error] = "Customer not found" and return unless @customer
  @jobs = @customer.jobs
  render :layout => 'home'
end
Greg
Perfect! Thank you Greg.
sscirrus