在我的测验中,我创建了一个带有数字的问题表,用于表示问题是否得到回答。如果它回答了答案表中的访问列,则转到1或者否则为0 如
+----+--------+--------------+---------+---------------+------------+-------+---------+
| id | answer | questions_id | user_id | exam_group_id | modules_id | marks | visited |
+----+--------+--------------+---------+---------------+------------+-------+---------+
| 1 | ans2 | 8 | 3 | 1 | 1 | 0 | 1 |
| 2 | NULL | 9 | 3 | 1 | 1 | 0 | 0 |
| 3 | NULL | 6 | 3 | 1 | 1 | 0 | 0 |
| 4 | ans1 | 5 | 3 | 1 | 2 | 1 | 1 |
| 5 | NULL | 4 | 3 | 1 | 2 | 0 | 0 |
| 6 | NULL | 3 | 3 | 1 | 2 | 0 | 0 |
+----+--------+--------------+---------+---------------+------------+-------+---------+
我在我的视图页面中根据访问情况检查了问题
<% @slno = 0 %>
<ul class="student_list">
<% @questions.each do |s| %>
<% @slno = @slno + 1 %>
<% if ((Answer.find_by_sql["SELECT visited from answers where questions_id=#{s.id}"]) == 1) %>
<li class="student_names">
<a href="#" id="<%=s.id%>" class="student-link" > <%= @slno %></a>
</li>
<% else %>
<li class="student_names2">
<a href="#" id="<%=s.id%>" class="student-link2" > <%= @slno %></a>
</li>
<% end %>
<% end %>
</ul>
但它会将错误视为错误的参数数量(0表示1)
答案 0 :(得分:1)
Answer.find_by_sql错了!在[]或()
<% @slno = 0 %>
<ul class="student_list">
<% @questions.each do |s| %>
<% @slno = @slno + 1 %>
<% if ((Answer.find_by_sql(["SELECT visited from answers where questions_id=#{s.id}"])) == 1) %>
<li class="student_names">
<a href="#" id="<%=s.id%>" class="student-link" > <%= @slno %></a>
</li>
<% else %>
<li class="student_names2">
<a href="#" id="<%=s.id%>" class="student-link2" > <%= @slno %></a>
</li>
<% end %>
<% end %>
</ul>
您不需要使用@slno
- 使用each_with_index
重构代码:
<ul class="student_list">
<% @questions.each_with_index do |s, index| %>
<% if ((Answer.find_by_sql(["SELECT visited from answers where questions_id=#{s.id}"])) == 1) %>
<li class="student_names">
<a href="#" id="<%=s.id%>" class="student-link" > <%= index %></a>
</li>
<% else %>
<li class="student_names2">
<a href="#" id="<%=s.id%>" class="student-link2" > <%= index %></a>
</li>
<% end %>
<% end %>
</ul>
答案 1 :(得分:1)
你需要将find_by_sql包装在()中,如下所示:
Answer.find_by_sql(["SELECT visited from answers where questions_id=#{s.id}"])
您也不需要在此实例中编写自己的SQL,而只需执行此操作:
<% if Answer.where(questions_id: s.id).count == 1 %>