I have a collection of Episodes which is connected to a Season and a Show.
I need to display them as such:
Show title
....Season number 1
........Episode name
........Episode name
....Season number 2
........Episode name
........Episode name
My controller:
def index
@show_ids = Following.find_all_by_user_id(current_user.id).collect(&:show_id)
@seen_ids = SeenEpisode.find_all_by_user_id(current_user.id).collect(&:episode_id)
if @seen_ids.any?
@episodes = Episode.find(:all, :conditions => ["show_id IN (?) AND episodes.id NOT IN (?)", @show_ids, @seen_ids], :joins => [:show, :season])
else
@episodes = Episode.find(:all, :conditions => ["show_id IN (?)", @show_ids], :joins => [:show, :season])
end
end
My view:
<ul>
<% @episodes.group_by(&:show).each do |show, episodes| %>
<li><h2><%= show.name %></h2></li>
<% episodes.group_by(&:season).each do |season, episodes| %>
<li><strong><%= season.number %></strong></li>
<% episodes.each do |episode| %>
<li><%= episode.name %></li>
<% end %>
<% end %>
<% end %>
</ul>
This works fine, although I know this is not a good method, and the performance is SHIT (like 10 seconds for about 150 records). How can I have a grouping like this with good performance?
Also, how can I refactor this?
if @seen_ids.any?
@episodes = Episode.find(:all, :conditions => ["show_id IN (?) AND episodes.id NOT IN (?)", @show_ids, @seen_ids], :joins => [:show, :season])
else
@episodes = Episode.find(:all, :conditions => ["show_id IN (?)", @show_ids], :joins => [:show, :season])
end