mercredi 17 juin 2015

Sum returns value when should return 0

I'm having a really confusing problem. Here it is:

[12] pry(EstimatedTime)> EstimatedTime.where(user_id: User.current.id, plan_on: date).pluck(:hours) => [] 
[13] pry(EstimatedTime)> EstimatedTime.where(user_id: User.current.id, plan_on: date).sum(:hours) => 3.0

What kind of magic is this?

This statement resides in model method, that is being called from view. Before that, in controller action, i'm calling another method of the same model, that is performing bulk create of records within transaction.

def self.save_all(records)
  transaction do
    records.each do |record|
      record.save!
    end
  end
  rescue ActiveRecord::RecordInvalid
    return false 
end

The exception is being thrown, method returns false, view is rendered and this happens.

UPD I found a workaround, replacing .sum with .pluck(:hours).sum, but I still have no idea why my first way of doing this fails.

Aucun commentaire:

Enregistrer un commentaire