Topic: undefined method `title' for nil:NilClass

I'm trying to learn Rails and finding it somewhat challenging.  I'm following the Agile Web Development with Rails 3.1 book.  The example they're working through is a shopping cart app.  It involves 3 models, a product, a cart, and a line_item.  Now the subject of my post is the error I'm getting which is coming from the following file app/views/carts/show.html.erb and looks like this:

<h2>Your Pragmatic Cart</h2>
<ul>
    <% @cart.line_items.each do |item| %>
    <li><%= item.product.title %></li>
    <% end %>
</ul>

<%= link_to 'Edit', edit_cart_path(@cart) %> |
<%= link_to 'Back', carts_path %>

The three models are connected somehow but I'm not sure I understand the process.  I will post the models.
The cart:
----------------------------------------------------------------
class Cart < ActiveRecord::Base
  has_many :line_items, dependent: :destroy
end
----------------------------------------------------------------

line_item:
----------------------------------------------------------------
class LineItem < ActiveRecord::Base
  attr_accessible :cart_id, :product_id
  belongs_to :product
  belongs_to :cart
end
----------------------------------------------------------------

product:
----------------------------------------------------------------
class Product < ActiveRecord::Base
  attr_accessible :title, :description, :image_url, :price, :id
 
  has_many :line_items
end
----------------------------------------------------------------

I don't know why it thinks title is a method when it's a class member.  Let me know if I should post more code.

thanks,
mike

Re: undefined method `title' for nil:NilClass

you should reference it when you are creating line_item. look at rails guide getting start example.

life is not short however you think to learn Rails

Re: undefined method `title' for nil:NilClass

That means that you get nil when calling

item.product

So check if product_id is set on the item you are getting.