保华的Rails学习笔记

搜索功能的添加

1)在index里边添加代码

def index
    jobs = Job.all
    if params[:search]
      @jobs = Job.published.search(params[:search])
    elsif
    @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
  end

2)在model里边添加代码

  def self.search(search)
      where("title LIKE ? OR description LIKE ? ", "%#{search}%","%#{search}%")
  end

3)在view页面添加代码,这里添加到jobs首页

<%= form_tag(jobs_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search jobs" %>
<%= submit_tag "Search" %>
<% end %>