Trung Tran
Trung Tran

Reputation: 13731

Child missing parent object rails 4.0

I have a Task Order model that has many Invoices. I am able to CRUD operations on them just fine. However, I was doing some testing where I deleted all Task Order and Invoice records and then I added an Invoice. Since there are parents available - ie no Task Orders - I get the error:

undefined method `invoices' for nil:NilClass 

for the code snippet

task_order.invoicedAmount = task_order.invoices.sum(:amount) + amount

The issue is it can't call "invoices" since there are no task orders to call invoices. However, in my invoice model I did include a validation to make sure the user selects a task order before adding in the invoice. Therefore, is there a way for me to get the validation to kick in BEFORE I get to that error page?

Upvotes: 1

Views: 44

Answers (1)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

From comment: add condition to this line

task_order.invoicedAmount = task_order.invoices.sum(:amount) + amount if task_order.present?

Upvotes: 1

Related Questions