I have this Rails code in a method in a controller. It takes four parameters, does a bit of math and I’d like it to return a the value stored in the ‘attendance’ variable to a partial in a view.
def find_attendance(lesson_id, student_id, start_date, end_date)
marks = Array.new
all_registers = Register.where(:lesson_id => lesson_id)
start_date.upto(end_date) do |date|
all_registers.each do |register|
if date == register.date
this_mark = RegisterMark.where(:student_id => student_id, :register_id => register.id)
this_mark.each do |mark|
marks << mark.mark
end
end
end
end
attendance = ((Float(marks.count("O")) + Float(marks.count("N"))) / Float(marks.count)) * Float(100)
end
I have created a _find_attendance.html.erb file in the relevant view directory, and tried calling the partial by using <%= render :partial => “find_attendance” %> but I’m having trouble passing parameters and using the correct variable name within the partial.
I’ve tried playing around with using instance variables on ‘attendance’.
Any pointers?
You almost certainly want to add this method as a method to the model. Maybe in your case the lesson model?
Then in your view you can get at the @lesson model to get attendance.
There’s some area for improvement in your loops, I included a simple way to loop through all Register for a Lesson above. You can do this for both your Register.where and your RegisterMark.where for speed improvements