I can’t seem to get this loop working correctly
@mr = MediaRating.where("user_id = ?", session['user_credentials_id'])
unless @mr.empty?
@mr.each do |rating|
@m = Media.where("id = ?", rating.media_id)
@m.each do |m|
@history << m
end
end
end
In the MediaRating table there is only 3 test rows of data, but when I output the data on the screen the @history array contains 9 entries. I know it has to do with something I am doing wrong with the loop, but can’t figure it out.
Working code
View:
<!-- For Each -->
<% unless @history.empty? %>
<% @history.each do |m| %>
<tr class="control_result_row">
<td class="control_result"><%= m.first.title %></td>
<td class="control_result">Russian</td>
</tr>
<% end %>
<% else %>
<tr class="control_result_row">
<td class="control_result" colspan="2">You have no ratings logged</td>
</tr>
<% end %>
<!-- End For Each -->
Controller:
@mr = MediaRating.where("user_id = ?", session['user_credentials_id'])
@mr.each do |rating|
@m = Media.where("id = ?", rating.media_id)
@history << @m
end
How many things are in the
Mediatable? If that returns 3 things for eachMediaRating, your loop is fine.Also,
unless @mr.empty?is not needed, because if@mris empty, theeachblock will do nothing.I think this is all you need:
@m = Media.where("id = ?", rating.media_id)should only return one thing ifidis a key.