在我的模型中,我有一个函数,结果数组是
...#<DailyStat subject: "Auditing Theory", topic: "Audit Planning", item_count: 3, correct_item_count: 0>
#<DailyStat subject: "Auditing Theory", topic: "Audit Reporting", item_count: 2, correct_item_count: 0>
#<DailyStat subject: "Auditing Theory", topic: "Audit Sampling", item_count: 2, correct_item_count: 2>...
(DailyStat是一个模特。) 我需要添加一定百分比的item_count / correct_item_count以保证准确性。如何转换并添加其他符号。这是当前的代码,它不起作用。
.select("subject, topic, sum(correct_item_count) as correct_item_count, sum(item_count) as item_count") # can't I just add the computation here
.map{|row| row} # Supposed to convert from AR record to array
.map{|row|
row[:accuracy] = row[:correct_item_count]/row[:item_count]
row
}
这种方法是否更好,或者我执行select语句时应该进行计算(哪个更快?)
答案 0 :(得分:0)
无需从SQL中获取它。数据库用于...数据,而不是计算。
您可以在DailyStat模型中轻松定义此类方法,并在需要时在视图或其他地方调用它。
class DailyStat < ActiveRecord::Base
def accuracy
return 0 if item_count == 0
correct_item_count/item_count
end
end
并使用它
stat = DailyStat.last
state.accuracy
# There is no SQL involved
答案 1 :(得分:0)
sql查询中的计算将比这更快。
你可以做这样的事情。
select("subject, topic, sum(correct_item_count) as correct_item_count, sum(item_count) as item_count, ((sum(item_count)/sum(correct_item_count))*100) as accuracy_percentage")