Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing only Objects from the past 30 days

Having finally manage to get my app to list jobs under specific dates. I am now looking to find a way to only show jobs created within the past 30 days.

At the moment my method for showing jobs sits in a partial and looks like this:

 <% @jobs.group_by{|x| x.created_at.strftime("%d %b. %Y")}.each do |date,jobs_on_that_date| %>

 <section class="date">
   <%= date %>
 </section>

 <section id="top-job">
   <% jobs_on_that_date.each do |job| %>
    <section id="job-wrapper">
      <%= link_to url_with_protocol(@link.job_url), :target => '_blank' do %>
      <section id="job">
        <%= job.title %> - <%= job.company %>
        <%= job.salary %>
        <%= job.location %> 
        <%= job.job_type %>
    </section>
 </section> 
<% end %>
 <% end %>
 </section>
 <% end %>

Is there way to integrate only showing the past 30 days worth of jobs in the view or would it be better to define this in the controller?

Thanks!

like image 282
Tom Pinchen Avatar asked Aug 02 '12 16:08

Tom Pinchen


2 Answers

It would be better to do in the controller. The less logic you put in the view, the better.

Assuming that @jobs is the result of an ActiveRecord query, @jobs = @jobs.where('created_at > ?', 30.days.ago) sounds like the query you want.

like image 68
Matt Burke Avatar answered Oct 14 '22 09:10

Matt Burke


I think the best way to do this is in the model, with a scope. Then your controller can use it.

# app/models/job.rb
class Job < ActiveRecord::Base
  # ...
  scope :recent, lambda{ where(['created_at > ?', 30.days.ago]) }
  # ...
end

# app/controllers/jobs_controller.rb
class JobsController < ApplicationController
  def show
    @jobs = Job.recent.group_by(&:created_at)
  end
end

# app/views/jobs/show.html.erb
<% @jobs.each do |date,jobs_on_that_date| %>

 <section class="date">
   <%= date.strftime("%d %b. %Y") %>
 </section>

 etc...

<% end %>

A slightly better way of handling the controller & view would be:

# app/controllers/jobs_controller.rb
class JobsController < ApplicationController
  helper_method :recent_jobs

  def show
    # just render...
  end

  protected

  def recent_jobs
    @_jobs ||= Job.recent.group_by(&:created_at)
  end
end

# app/views/jobs/show.html.erb
<% recent_jobs.each do |date,jobs_on_that_date| %>

 etc...

<% end %>

So there is no instance variable copying, and you have a nice controller AP I to use for getting your records.

You could also think about using a decorator to wrap your job object and provide the date-formatting logic there.

like image 31
Matt Van Horn Avatar answered Oct 14 '22 09:10

Matt Van Horn