Rails:在循环中调用函数会为每次迭代返回相同的值

时间:2013-02-21 06:51:53

标签: ruby-on-rails-3 loops methods ruby-on-rails-3.2

我正在尝试计算特定学生“UG10001”在特定月份从mysql数据库中的离开表中获取的离开。我正在使用以下代码片段 -

def calculate(student_id)

 leave = Leave.find_by_sql("SELECT leave_duration FROM leaves WHERE MONTH(leave_from) = 2
  AND YEAR(leave_from) = 2013 AND MONTH(leave_to) = 2 AND YEAR(leave_to) = 2013 AND
  academic_status = 'APPROVED' AND warden_status = 'APPROVED' AND student_id = student_id 
  AND status = 'ACTIVE'")

 sum = leave.sum(&:leave_duration)
 return sum

end

---------- ----------更新

  def calculate(student_id)

 sum = Leave.find_by_sql("SELECT leave_duration FROM leaves WHERE MONTH(leave_from) = 2
  AND YEAR(leave_from) = 2013 AND MONTH(leave_to) = 2 AND YEAR(leave_to) = 2013 AND
  academic_status = 'APPROVED' AND warden_status = 'APPROVED' AND student_id = student_id 
  AND status = 'ACTIVE'").sum(&:leave_duration)

 return sum
#it did the trick for me.
end

上述方法将计算特定学生在2013年2月份的假期,并将叶子总和返回给调用函数。

def calcuateLeaveForEachStudent
  array = Leave.find_by_sql("select student_id from students")
  c = Array.new
  for i in 0...array.length
     student_id = array[i].student_id
     c[i] = calculate(student_id) 
  end
end

但是当我调用上面的方法时,'calculate'方法在每次迭代时返回相同的值。这可能是什么解决方案..?在此先感谢..!

PS -
代码在Rails控制台上运行完美,没有任何语法错误,但是有一些我无法弄清楚的错误。

1 个答案:

答案 0 :(得分:0)

 calculate(operation, column_name, options = {}).

或者您可以参考link