step 1 add_column
首先rails g migration add_category_to_job
在新增的db/migrate/2017xxxx_create_category_to_job.rb
文件中添加
def change
add_column :jobs, :category_name, :string, default: "工程师"
end```
然后`rake db:migrate`
###step 2 GEM
在Gemfile中添加
gem 'ransack'
gem 'paginate'
gem 'paginate-bootstrap
然后 `bundle install`;
###step 3 搜索框
在Navbar增加一个搜索框
<%= form_tag search_jobs_path, :method => :get, class: "navbar-form navbar-right" do %>
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="搜索职位、公司" value="<%= params[:q] %>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="fa fa-search" aria-hidden="true"></i>
</button>
</div>
</div>
<% end %>
###step 4 控制器
在jobs_controller中增加相应的函数
def search
if @query_string.present?
search_result = Job.ransack(@search_criteria).result(distinct: true)
@jobs = search_result.paginate(:page => params[:page], per_page: 10 )
puts @jobs
else
@jobs = Job.publish.recent.paginate(page: params[:page], per_page: 10)
puts @jobs
end
end
在`private`下面添加
def validate_search_key
@query_string = params[:q].gsub(/\|'|/|?/, "") if params[:q].present?
@search_criteria = search_criteria(@query_string)
end
def search_criteria(query_string)
{ :title_or_description_or_contact_email_or_location_or_company_or_category_cont => query_string }
end
#注意: 这里搜索是会报错,是因为没有对应的view显示搜索结果(图中标注文字可以忽略)![](http://upload-images.jianshu.io/upload_images/2471238-3797d9e47da1d683.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
###step 5 VIEW
生成搜索结果所需要的对应页面 `touch app/views/jobs/search_result.html.erb`
<% if @jobs.length > 0 %>
<table class="table table-hover table-boldered table-striped custab">
<thead>
<tr>
<th>职位名称</th>
<th>工作类型</th>
<th>薪金</th>
<th>公司名称</th>
<th>公司地点</th>
<th>发布时间</th>
</tr>
</thead>
<tbody>
<% @jobs.each do |job| %>
<tr>
<td> <%= link_to(job.title, job_path(job)) %></td>
<td><%= job.category %></td>
<td> <span class="label label-success"><%= job.wage_lower_bound %>K - <%= job.wage_upper_bound %>K</span></td>
<td><%= link_to(job.company, '/jobs/search?utf8=✓&q=' + job.company) %></td>
<td><%= job.location %></td>
<td><%= job.created_at %></td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<h4 class="text-center">没有相关职位,尝试搜索其他的关键字</h4>
<div class="text-center">
<a class="btn btn-lg btn-info" href="/jobs">浏览职位</a>
</div>
<% end %>```
重新搜索试试看?😄