使用:collection时,如何在Rails中减少此VIEW中的循环次数?

时间:2010-05-27 03:54:31

标签: ruby-on-rails collections loops

我正在使用:collection来浏览属于给定广告系列的所有联系人。

但在该广告系列中,我会检查三种不同的模型(每种都有自己的部分模型)。感觉就像我正在查看联系人列表3x。我怎样才能让这个更精简呢?

<h2>These are past due:</h2>

<% @campaigns.each do |campaign| %>
   <h3>Campaign: <%= link_to campaign.name, campaign %></h3>
   <strong>Emails in this Campaign:</strong>
   <% for email in campaign.emails %>
      <h4><%= link_to email.title, email  %> <%= email.days %> days</h4>

         <% @contacts= campaign.contacts.find(:all, :order => "date_entered ASC" )%> <!--contacts collection-->   

         <!-- render the information for each contact -->
         <%= render :partial => "contact_email",
                    :collection => @contacts,
                    :locals => {:email => email} %>
    <% end %>

       Calls in this Campaign:
       <% for call in campaign.calls %>
          <h4><%= link_to call.title, call  %> <%= call.days %> days</h4>
          <% @contacts= campaign.contacts.find(:all, :order => "date_entered ASC" )%> <!--contacts collection-->      
         <!-- render the information for each contact -->
         <%= render :partial => "contact_call",
                    :collection => @contacts,
                    :locals => {:call => call} %>
       <% end %>

       Letters in this Campaign:
       <% for letter in campaign.letters %>
          <h4><%= link_to letter.title, letter  %> <%= letter.days %> days</h4>
          <% @contacts= campaign.contacts.find(:all, :order => "date_entered ASC" )%> <!--contacts collection-->      
         <!-- render the information for each contact -->
         <%= render :partial => "contact_letter",
                    :collection => @contacts,
                    :locals => {:letter => letter} %>
       <% end %>
<% end %>

1 个答案:

答案 0 :(得分:1)

如果您希望按类型(联系人,电子邮件,信件等)排序,我认为您无法提高效率(仅将重复代码提取到单独的部分和渲染集合中:

<% @contacts = campaign.contacts.find(...) %>
<% [:emails, :calls, :letters].each do |asset| %>
  <h4><%= asset.humanize %> in this campaign</h4>
  <%= render :partial => 'asset', :collection => campaign.send(asset), :as => :asset %>
<% end %> 

然后在_asset部分内部,您可以使用asset变量来引用当前的目标并通过@contacts实例变种来联系联系人。