Development log: ActionView::Template::Error (undefined method `name' for nil:NilClass):
ruby-on-rails, ruby-on-rails-3.2
Solution
In your database i suspect some of your product data does not contain sold_by_id or user_id. So its getting product.user nil as no user is associated with the product. Instead of
<%= product.user.name %>
use
<%= product.user.name if product.user %>
to skip this exception.
So your index.html.erb becomes
<% lots_of_products = Product.includes(:user).all %>
<ul>
<% lots_of_products.each do |product| %>
<li>
Product Name: <%= product.name %> costs $<%= product.price %>
Sold by <%= product.user.name if product.user %>
</li>
<% end %>
</ul>
Problem
I'm a newbie and this is for the Rails tutorial by Richard Schneeman. This is all that is in my index.html.erb file in my view/products folder. ``` <% first_product = Product.first %> <% lots_of_products = Product.includes(:user).all %> <ul> <% lots_of_products.each do |product| %> <li> Product Name: "<%= product.name %>"" costs $<%= product.price %> Sold by <%= product.user.name %> </li> <% end %> </ul> ``` The issue is with `<%= product.user.name %>`, which gives the error: NoMethodError in Products#index undefined method `name' for nil:NilClass. My controller files are vanilla and my routes.rb has: ``` ControllerExercise::Application.routes.draw do get '/products' => 'products#index' resources :users end ``` This is in the models: ``` class Product < ActiveRecord::Base belongs_to :user attr_accessible :name, :price end class User < ActiveRecord::Base has_many :products attr_accessible :job_title, :name end ``` Any and all help is greatly appreciated.