具有radio_button形式的数据库元素列表

时间:2013-12-02 21:29:35

标签: ruby-on-rails forms flash radio-button

我正在尝试构建一个多选题考试Web应用程序,以便您可以根据搜索条件检索一堆问题,然后回答问题并获得有关您是否正确回答的反馈。

我的questions_controller有以下方法:

def check_answer
  @question = Question.find(params[:id])
  if params[:response] == @question.answer
    @outcome = 'correct'
  else 
    @outcome = 'incorrect'
  end  
    flash[:notice] = "That is #{@outcome}."
    redirect_to :back

布局索引为:

<% @questions.each do |question| %>
    <h4> <%= question.stem %></h4>
    <%= form_tag "/check_answer/#{question.id}", :method => 'get' do%>
    <%= radio_button_tag "response", "a" %> <%= question.option_a%>
        <%= radio_button_tag "response", "b" %> <%= question.option_b%>
    <%= radio_button_tag "response", "c" %> <%= question.option_c%>
    <%= radio_button_tag "response", "d" %> <%= question.option_d%>
    <%= radio_button_tag "response", "e" %> <%= question.option_e%>     
    <%= submit_tag "Check Answer" %>
<% end %>

<% if flash[:notice] %>
<div class = "notice"><%= flash[:notice] %></div>
<% end %>

然而,当我选择其中一个单选按钮时,它会在每个问题的底部返回“正确(正确)”。这是有道理的,基于代码,我不知道如何更改它,所以它只显示在1个问题的底部“是正确的”,你点击“检查答案”框。

1 个答案:

答案 0 :(得分:0)

根据您的问题,尝试添加一段逻辑来注释结果。

查看:

<% @correct_field ||= nil %>
<% @questions.each do |question| %>
  <h4> <%= question.stem %></h4>
    <%= form_tag "/check_answer/#{question.id}", :method => 'get' do%>
      <%= radio_button_tag "response", "a" %> <%= question.option_a%><% "CORRECT!" if @correct_field == "a" %>
      <%= radio_button_tag "response", "b" %> <%= question.option_b%><% "CORRECT!" if @correct_field == "b" %>
      <%= radio_button_tag "response", "c" %> <%= question.option_c%><% "CORRECT!" if @correct_field == "c" %>
      <%= radio_button_tag "response", "d" %> <%= question.option_d%><% "CORRECT!" if @correct_field == "d" %>
      <%= radio_button_tag "response", "e" %> <%= question.option_e%><% "CORRECT!" if @correct_field == "e" %>     
     <%= submit_tag "Check Answer" %>
    <% end %>

控制器:

def check_answer
  @question = Question.find(params[:id])
  if params[:response] == @question.answer
    @correct_field = @params[:response]
    @outcome = 'correct'
  else 
    @outcome = 'incorrect'
  end  
  flash[:notice] = "That is #{@outcome}."
  redirect_to :back

在控制器中,只需将@correct_field设置为params中任何一个解析为表示选择的字符串,如上所述。

那就是说,我不是这样做的。感觉有点像应该使用partials和/或JavaScript和AJAX调用来解决的问题。希望无论如何都有帮助。