Reputation: 2497
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!
Upvotes: 9
Views: 9347
Reputation: 1644
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.
Upvotes: 4
Reputation: 3326
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.
Upvotes: 27