开发者

Call backs in Rails

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开发者_如何学JAVA.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!


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.


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜