Rails使用link_to更改引导列表项的颜色

时间:2016-10-08 03:25:02

标签: ruby-on-rails twitter-bootstrap

我试图根据是否选择了正确的问题答案来更改引导程序列表项的颜色......但使用link_to会使其变得复杂。建议表示赞赏。 THX。

    <ul class="list-group" id="answered">

    <% @question.answers.each do |answer| %>

  <%= link_to(answer.text, question_path(@question, attempted_answer: answer.id), :class => "list-group-item") %>
         <% if @attempted_answer && @attempted_answer == answer %>
         <% if @attempted_answer.correct %>

          correct
            <% else %>
              incorrect
            <% end %>
          <% end %>

1 个答案:

答案 0 :(得分:2)

在帮助文件中创建一个方法,如下所示

def correct_answer(attempted_answer, answer)
  return false unless attempted_answer
  attempted_answer == answer && attempted_answer.correct   
end

然后在视图中调用helper方法

<%= link_to(answer.text, question_path(@question, attempted_answer: answer.id), :class => "list-group-item #{correct_answer?(@attempted_answer, answer) ? 'list-group-item-success' : 'list-group-item-danger'}") %>
  <% correct_answer?(@attempted_answer, answer) ? 'correct' : incorrect %>  
<% end %>