Search code examples
ruby-on-railsruby-on-rails-3.1

Listing objects under the date they were created


Sorry for the amateur question but I am still quite new to rails. I currently have an app that creates jobs and I would like to display the jobs beneath the date they were created in the same way they do on Dribble

At the moment to display the jobs I have te following:

 <% @jobs.each do |job| %>
   <div class="job-wrapper"><%= link_to user_job_path(job.user_id ,job) do %>
    <div class="job">
     <div class="job-desc"><strong><%= job.company %></strong> are looking for a <strong><%= job.job_title %></strong>
      <div class="job-sal"><%= job.job_salary %></div>
     </div>
    </div>
   </div>
  <% end %>
  <% end %>

I am sure I need to create a loop of some kind to make this work but am unsure how to incorporate it so that the date only displays once at the top of the jobs and then all jobs created during that date are shown?

Any help would be much appreciated! Thanks


Solution

  • Try the pattern below --

    <% @job.group_by{|x| x.created_at.to_date }.each do |date,jobs_on_that_date| %>
      <%= date %>
      <% jobs_on_that_date.each do |job| %>
        # render the job
      <% end %>
    <% end %>
    

    Basically you need to group your jobs by the date (or whatever you want to group on) then get a hash keyed on the stuff you grouped on. Then render the key (date) followed by the list of objects relating to that key.