1

我为答案创建了一个问题,如果答案正确,则设置 1 分。该列的总数将显示在另一页中。请帮助我

def next
@ans_id = 1
@user = current_user
@student = Student.find_by_admission_no(@user.username)
@exam_group = ExamGroup.find_by_id(params[:exam_group_id])
@answer = Answer.new(params[:ans])
@answer.answer = params[:answer]
@answer.exam_group_id = @exam_group.id
@answer.user_id = @user.id
passed_question = params[:passed_question]
@answer.questions_id = passed_question
@question = Question.find_by_id(passed_question)
if params[:answer] == @question.is_answer
  @answer.marks = 1
else
  @answer.marks = 0
end
if @answer.save
  @ans_id = @ans_id + answered.count
  @ans = Question.find_by_id(left_random, :conditions => ['id not in (?) && exam_group_id=?',answered, @exam_group])
  render(:update) do |page|
    page.replace_html 'main', :partial => 'ans', :object => @ans
  end
end
end

并且数据库是

+----+--------+--------------+---------+---------------+------------+-------+
| id | answer | questions_id | user_id | exam_group_id | modules_id | marks |
+----+--------+--------------+---------+---------------+------------+-------+
|  1 | ans1   |            1 |       3 |             1 |       NULL |     1 |
|  2 | ans2   |            2 |       3 |             1 |       NULL |     1 |
|  3 | ans3   |            3 |       3 |             1 |       NULL |     0 |
|  4 | ans2   |            4 |       3 |             1 |       NULL |     0 |
+----+--------+--------------+---------+---------------+------------+-------+

我想对标记列求和并将其显示在该控制器的另一个页面中

@exam_group = ExamGroup.find(params[:exam_group])
  @student = Student.find_by_id(params[:student])
  @batch = @student.batch
  @modules = StudentAdditionalField.find(:all)
  @total = Answer.sum(:marks)
  @exams = []
  @modules.each do |mod|
    @exams.push mod.name unless mod.name.nil?
    @exams.push mod.marks unless mod.marks.nil?
    @exams.push total unless total.nil?
  end

和显示视图是

      <% @exams.each do |es| %>
    <tr class="tr-<%= cycle('odd', 'even') %>">
      <td class="col-1"> <%= es.name %></td>
        <td class="col-1"><%= es.marks || '-' %></td>
        <% total_marks_attained = @total %>
        <td class="col-1"><%= es.marks %></td>
        <% total_max_marks = @total %>
      </td>
    </tr>
  <% end %>

提前感谢

4

1 回答 1

0

所以从您发布的内容来看,您似乎需要使用sumActiveRecord的功能:

Model.where("user_id = ?", current_user.id).sum(:marks)

但是,您的代码似乎没有遵循 Rails 约定。具体来说,您没有使用 ActiveRecord 关系,例如belongs_toor has_many。如果你使用这些,你真的可以打电话@user = User.find(current_user.id),你会得到他们的所有标记,如下所示:@user.marks

于 2013-10-18T08:26:22.477 回答