Rails has_many: undefined method `*' for nil:NilClass -


I have a definition where there are several order items for an order:

  class order & Lt; ActiveRecord :: Base has_many: order_items and class order entom & lt;  

Order and order items are stored properly and with their relationships.

I'm trying to display a record of all orders. For this I need to access some features from order items, such as amount or value

I have defined the following method to calculate the total value of the order, and it has the command model:

  def total order_items. Inject (0) {| Sum, n | N.price * n.amount + sum} end  

I tracked the error and I came to know that I am getting the error in this method, this is the error: ActionView: : Template: Error (Undefined method * 'for zero: NilClass): `

To display the total value of the order, the view is called.

Actually if I add some line to this method, where I try to use any order item attribute, then order_items [0]. Price says I get an error.

I do

I have the exact same relationship defined as ShoppingCart and ShoppingCartItems and this problem Did not face it.

In addition, the order and order items I am developing are similar to the previous project, which I did with Rail 3.2.9, and it works fine.

What can I do?

You have OrderItem with value Or amount VA Lue

To verify that there is no value in OrderItem entries, OrderItem.where (value: zero) ; And for the amount of OrderItem.where (Zodiac: zero)

To consider the amount in the form of these zero prices / 0, your code Change to:

  def total order_items.map {| Oi | (Oi.price || 0) * (oi.amount || 0)} .sum end  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -