1

I can't find very good intros to specific callbacks in rails.

Basically I'm dealing with two models:

  1. Order
  2. Item, (nested in Order form)

I'm using the before_update model to do some basic math:

 class Order < ActiveRecord::Base
        accepts_nested_attributes_for :line_items
        before_update :do_math
protected
def do_math
  self.req_total = self.line_items.sum(:total_price)
end

req_total is the total value of the order, when a user updates the amounts I need to add up the total_price of the line_items. What am I doing wrong? My logic fails to read the newly submitted total_price.

Thanks!

JZ.
  • 21,147
  • 32
  • 115
  • 192
  • 1
    Probably best if you outline what's going wrong – Chris McCauley Feb 17 '10 at 21:53
  • The above code produces the old sum of the total_prices, not the modified total_price from the user submitted form. I think its doing an Sql query on total_price, I'm trying to now follow some of the suggestions below. – JZ. Feb 17 '10 at 22:14
  • The line_items.sum call will indeed hit the database again. "sum" is an ActiveRecord method ... need to look at using the array values directly and your own sum algorithm using the array or enumerable methods. – Toby Hede Feb 17 '10 at 22:32

2 Answers2

0

Not sure about your use of sum - looks like your trying to use SQL when talking Ruby!

Try How to sum array of numbers in Ruby?

Hope that helps :)

Community
  • 1
  • 1
Paul Groves
  • 3,983
  • 2
  • 23
  • 24
0

Look at your log. The sum method does a SQL sum from the database. In that case, it may not be working since the child model (line_items) members may not have been saved to the db yet.

As an alternative, try

self.req_total = 0
line_items.each{|item|self.req_total += item.total_price}   

ps. The sum method for ActiveRecord associations is not the same sum method as for enumerables, regular arrays, etc. The ActiveRecord sum method is really the calculate(:sum) method.

Larry K
  • 47,808
  • 15
  • 87
  • 140