How can I refactor out needing so many for-loops in rails?
Posted
by Angela
on Stack Overflow
See other posts from Stack Overflow
or by Angela
Published on 2010-05-15T04:10:19Z
Indexed on
2010/05/15
4:14 UTC
Read the original article
Hit count: 331
ruby-on-rails
|for-loop
I need help refactoring this multi-loop thing. Here is what I have:
Campaign has_many Contacts Campaign also has many templates for EVent (Email, Call, and Letter).
I need a list of all the Emails, Calls and Letters that are "overdue" for every Contact that belongs to a Campaign. Overdue is determined by a from_today method which looks at the date the Contact was entered in the system and the number of days that needs to pass for any given Event. from_today() outputs the number of days from today that the Event should be done for a given Contact.
Here is what I've done, it works for all Emails in a Campaign across all contacts. I was going to try to create another each do loop to change the class names.
Wasn't sure where to begin: named_scope, push some things into a method, etcetera, or -- minimum to be able to dynamically change the class names so at least it loops three timees across the different events rather than repeating the code three times:
<% @campaigns.each do |campaign| %>
<h2><%= link_to campaign.name, campaign %></h2>
<% @events.each do |event| %>
<%= event %>
<% for email in campaign.emails %>
<h4><%= link_to email.title, email %> <%= email.days %> days</h4>
<% for contact in campaign.contacts.find(:all, :order => "date_entered ASC" ) %>
<% if (from_today(contact, email.days) < 0) %>
<% if show_status(contact, email) == 'no status'%>
<p> <%= full_name(contact) %>
is <%= from_today(contact,email.days).abs%> days overdue:
<%= do_event(contact, email) %>
</p>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
© Stack Overflow or respective owner