Go through several 2d tables and sort them

advertisements

I'm pretty new to ruby and rails and I'm building my first application. I've got a method (enroll_again) that goes through all of an Agents contracts and sorts them by which is expiring soonest. This method returns a 2d array with [[Agentname, numdays]]. I'm trying to run this method at a higher level for all contracts on all accounts.

<% @accounts.each do |account| %>
    <% account.contracts.enroll_again.each do |x,y| %>
        <li>
            <%= "#{y} Days remain on \n #{x}" %>
        </li>
    <%end%>
 <%end%>

This code above returns a list of sorted elements specific to an account but the entire list remains unsorted. I tried putting all of the elements returned by the enroll_again into a separate array but my syntax must be wrong because it always returns an empty list.
edit :

def self.enroll_again
  d= Date.today
  contract = Contract.all
  temp = contract.map do |x|
    [
      Account.where(:accounts => { :id => x.account_id }).first.name),
      ((Date.strptime(x.startd,'%m/%d/%Y') + x.duration.months)-d).to_i
    ]
  end
  temp.sort_by{|x,y|y}
end


you should be able to do the following

<% @accounts.each do |account| %>
  <% account.contracts.sort_by(&:remaining_days).each do |contract| %>
    <li>
      <%= "#{contract.remaining_days} Days remain on \n #{account.name}" %>
    </li>
  <%end%>
<%end%>

def remaining_days
  @remaining_days ||= ((Date.strptime(startd,'%m/%d/%Y') + duration.months) - Date.today).to_i
end

This, I think is easier to understand plus you can reuse the remaining_days method.