简体   繁体   中英

Clearly defined Rails routing problem - undefined method for Nil:NilClass

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.

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

undefined method 'name' for Nil:NilClass

#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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM