如何在Rails中重构简单的过滤器操作?

时间:2013-01-21 20:46:27

标签: ruby-on-rails ruby ruby-on-rails-3 refactoring

我想使用两个参数过滤我的@jobs

现在我有这样的事情:

  def filter
    if params[:filter][:trade].present? && params[:type].present?
      @jobs = Job.accepted.with_accepted_company.where(:trade_id => params[:filter][:trade],:job_type =>params[:type])
      render :index
    elsif params[:filter][:trade].present?
      @jobs = Job.accepted.with_accepted_company.where(:trade_id => params[:filter][:trade])
      render :index
    elsif params[:type].present?
      @jobs = Job.accepted.with_accepted_company.where(:job_type =>params[:type])
      render :index
    else
      redirect_to jobs_path
    end
  end

2 个答案:

答案 0 :(得分:3)

def filter
  filters = {
    :trade_id => params[:filter][:trade],
    :job_type => params[:type]
  }

  filters.delete_if { |key,value| value.blank? }

  if filters.count > 0
    @jobs = Job.accepted.with_accepted_company.where(filters)
    render :index
  else
    redirect_to jobs_path
  end
end

答案 1 :(得分:-1)

 def filter
  h = {}
  params[:filter][:trade].tap{|v| h[:trade_id] = v if v.present?}
  params[:type].tap{|v| h[:job_type] = v if v.present?}
  if h.empty?
    redirect_to jobs_path
  else
    @jobs = Job.accepted.with_accepted_company.where(h)
    render :index
  end
end