目标:
- 首页可以按照职缺薪资下限排序
- 首页可以按照职缺薪资上限排序
- 首页可以按照职缺发表时间排序
- 把
Job.where(:is_hidden => false").order("created_at DESC") 重构成 Job.published.recent
Step1: 将薪资上限、薪资下限加入首页职缺表
修改app/views/jobs/index.html.erb
的<table>
<table class="table table-boldered">
<thead>
<tr>
<td>
职缺</td>
<td>薪资下限</td>
<td>薪资上限</td>
<td>刊登时间</td>
</tr>
</thead>
<tbody>
<% @jobs.each do |job| %>
<tr>
<td>
<%= link_to(job.title, job_path(job) %>
</td>
<td>
<%= job.wage_lower_bound %>
</td>
<td>
<%= job.wage_upper_bound %>
</td>
<td>
<%= job.created_at %>
</td>
</tr>
<% end %>
</tbody>
</table>
Step2:加上下拉选单
改app/views/jobs/index.html.erb
,在 <table>
之前加入“下拉选单”
<div class="dropdown clearfix pull-right">
<button class="btn btn-default dropdown-toggle"
type="button" id="dropdownMenuDivider" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="true">
排序
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuDivider">
<li>
<%= link_to("按照薪资下限排序", jobs_path(:order => "by_lower_bound")) %>
</li>
<li>
<%= link_to("按照薪资上限排序", jobs_path(:order => "by_upper_bound")) %>
</li>
<li>
<%= link_to("按照发表时间排序", jobs_path ) %>
</li>
</ul>
</div>
Step3 建立published
scope
app/models/job.rb
class Job < ApplicationRecord
...
scop :published, -> { where(is_hidden:false) }
scop :recent, -> { order('created_at DESC') }
end
app/controllers/jobs_controller.rb
def index
@jobs = case params[:order]
when 'by_lower_bound'
Job.published.order('wage_lower_bound DESC')
when 'by_upper_bound'
Job.published.order('wage_upper_bound DESC')
else
Job.published.recent
end
end
commit