darkginger
darkginger

Reputation: 690

Assign action in Rails based on the rank in .order

In my Scoreboard controller, I am setting an order, and I am stack ranking the results by score:

 @Quizzes = Quiz.where(finished: true, category: session[:category]).order(score: :desc).limit(10)

That returns a table of the top 10 results in a table. I now want to put a message next to the first place (top ranked) result and a different message for the rest of the results. So I tried to create an if/else using first!:

  <% if Quiz.where(category: session[:category]).first! %>
     <td>You win</td>
  <% else %>
    <td>You lose</td>
  <% end %> 

This does add "You win" to the view, but it is doing it for the final result (#10) and the else message is not appearing at all. I tried switching it to .last as well, but the same thing happened.

Assuming you can use .order as a way to pick a result, how should I adapt this?

UPDATE

Adding full code for rendering the score table:

  <% @quizzes do |quiz| %>
    <tr>
     <td></td>
     <td><%= quiz.user.username %></td>
     <td><%= quiz.user.city %></td>
     <td><%= quiz.category %></td>
     <td><%= quiz.score %></td>
     <% end %>

  <% @quizzes.each_with_index do |quiz, index| %>
    <% if index == 10 %>
        <td>You Win</td>
     <% else %>
        <td>You lose</td>
    <% end %>
    <% end %>
</tr>

Upvotes: 1

Views: 83

Answers (3)

aliibrahim
aliibrahim

Reputation: 1985

This is what you should do:

<% @quizzes.each_with_index do |quiz, index| %>
    <tr>
     <td></td>
     <td><%= quiz.user.username %></td>
     <td><%= quiz.user.city %></td>
     <td><%= quiz.category %></td>
     <td><%= quiz.score %></td>
     <% if index == 0 %>
        <td>You Win</td>
     <% else %>
        <td>You lose</td>
     <% end %>
    </tr>
<% end %>

Upvotes: 3

Jawad Khawaja
Jawad Khawaja

Reputation: 756

Assuming you have the ten scores in @top_ten = Quiz.where(finished: true, category: session[:category]).order(score: :desc).limit(10)

You can do the following:

<% @top_ten.each_with_index do |quiz, index| %>
    <% if index == 0 %>
        <td>You Win</td>
    <% else %>
        <td>You lose</td>
    <% end %>
<% end %>

Upvotes: 0

Spacepotato
Spacepotato

Reputation: 144

Try something like this:

<% @Quiz.each do |quiz| %>
  <% if quiz == @Quiz.first %>
    <td>You win</td>
  <% else %>
    <td>You win</td>
  <% end %>
<% end %>

As .first returns the first object of a collection, not whether or not the object is the first object. That being said you could also do:

<% @Quiz.each_with_index do |quiz, index| %>

And just check whether index == 0 to determine if it is the first object.

Upvotes: 0

Related Questions