13 Oct 2013, 07:24
Generic-user-small

Bin Yang (2 posts)

Hi,

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
			line_item.save
		end
  end
 
end 

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| %>
		<tr>
			<td><%= item.quantity %>&times;</td>
			<td><%= item.product.title %></td>
			<td class="item_price"><%= number_to_currency(item.total_price) %></td>
		</tr>
	<% end %>

Can you please explain what causes it?

Thanks for your time

Bin Yang

18 Oct 2013, 22:12
Generic-user-small

Bin Yang (2 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.

Thanks

  You must be logged in to comment