SouravMoitra
SouravMoitra

Reputation: 63

rails each iterator iterating two times

I am trying to get some nested queries to get some objects. Here is some of the code

stream_controller.rb

def show
  @rank = Rank.where(user_id: Application.where(stream_id: @stream.id))
end

show.html.erb

<% i = 1 %>
<% @rank.each do |f| %>
  <tr>
    <td><%= i %></td>
    <td><%= f.user_id %></td>
    <td><%= User.find(f.user_id.to_i).name %></td>
    <td><%= f.rank %></td>
  <tr><br>
  <% i += 1 %>
<% end %>

The problem is the output is:

Sr  User id     Name    Rank
1   15  a16 2
2   7   a7 a71  4
3   8   a8 a81  6
4   13  a14 a41 8
5   1   a1  13
6   4   sm  14
7   15  a16 2
8   7   a7 a71  4
9   8   a8 a81  6
10  13  a14 a41 8
11  1   a1  13
12  4   sm  14

That is its iterating two time why is that happening ? and how can it be prevented?

Upvotes: 0

Views: 113

Answers (3)

SouravMoitra
SouravMoitra

Reputation: 63

I wrote a sql statement and it solved my problem and put in model file and called it from controller on button click it solved my problem

def self.generate_result(stream_id)
sql = "select distinct user_id, rank from ranks where
       user_id = any(
       select user_id from applications where stream_id =
       #{stream_id}
       and verified = true)
       order by rank asc"
ActiveRecord::Base.connection.execute(sql)

end

Upvotes: 0

John C
John C

Reputation: 4396

Try this:

@rank = Rank.where(user_id: Application.where(stream_id: @stream.id)).uniq

The .uniq (at the end of the line) will remove any duplicate rows returned by your query.

Upvotes: 0

Max Williams
Max Williams

Reputation: 32933

I'm not 100% sure what you're trying to do but your code could be tidied up quite a bit. Here's a nicer way to do your loop: since @rank is a collection variable i've renamed it to @ranks in keeping with convention.

<% @ranks.each_with_index do |rank, i| %>
  <tr>
    <td><%= i + 1 %></td>
    <td><%= rank.user_id %></td>
    <td><%= rank.user.name %></td>
    <td><%= rank.rank %></td>
  <tr><br>
<% end %>

Upvotes: 1

Related Questions