简体   繁体   English

如何在Rails中计算学科百分比

[英]How to calculate a subjects percentage in Rails

My problem is about calculating a subjects percentage. 我的问题是关于计算科目百分比。 I have the EnterMark model. 我有EnterMark模型。 Which contains the section_id. 其中包含section_id。 Using that I can get the number of students in a particular section. 使用它,我可以获得特定部分的学生人数。 But the problem comes about when calculating the percentage for each subject (In chart view). 但是问题出在计算每个主题的百分比时(在图表视图中)。

Controller 调节器

@mark_percent = EnterMark.where(:school_id => params[:school], :course_id =>  params[:course], :section_id => params[:view])

View 视图

<% @mark_percent.each do |i| %>     
  <% @count = i.students.count %> 
    ['<%= i.subject.subject %>', <%= (i.subject_mark_total) / @count  %>],
<% end %>

But @count not taken for each subject. 但是@count不是每个科目都采用的。 Please help. 请帮忙。

我认为这是您想要的:

per = "#{(i.subject_mark_total.to_f / @count) * 100}%"

So you're trying to find an average for each course, is that right? 因此,您正在尝试查找每个课程的平均值,对吗? Like Pierre-Louis Gottfrois said, you should try to not define variables inside the view. 就像Pierre-Louis Gottfrois所说的那样,您应该尽量不要在视图内部定义变量。

In the Course.rb model you could make something like this: 在Course.rb模型中,您可以执行以下操作:

def avg
  total = self.subject_mark_total.to_f
  students = self.students.count
  # get average of scores and round to two decimal places
  average = total / students
  average.round(2)
end

and in the view call <%= course.avg %> 并在视图中调用<%= course.avg %>

Apologies if i've misunderstood what you're asking for! 抱歉,如果我误解了您的要求!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM