small medium large xlarge

13 Oct 2013, 07:24
Bin Yang (4 posts)


I had the error “undefined method ‘price’ for nil:NilClass” in the code below:

class SetPriceValueInLineItems < ActiveRecord::Migration
  def up
		LineItem.all.each do |line_item|			
			line_item.price = line_item.product.price

I do have a few line_item.product, but if I access line_item.product.price, it shows Nil class error. In the code below, item.product.title can be accessible, I tried to use “puts” command to display the item.product.title in the console window from the migration code above, it showed the same error “no title method in nil Class”. So in migration context, I cannot access the attribute in a chain.

<% @cart.line_items.each do |item| %>
			<td><%= item.quantity %>&times;</td>
			<td><%= item.product.title %></td>
			<td class="item_price"><%= number_to_currency(item.total_price) %></td>
	<% end %>

Can you please explain what causes it?

Thanks for your time

Bin Yang

18 Oct 2013, 22:12
Bin Yang (4 posts)

I found the cause of the failure, my table has some records which don’t valid product_id that is foreign key to get product.

Delete them, then problem is fixed.


You must be logged in to comment