Setting default search parameter on Ransack for rails

ε祈祈猫儿з 提交于 2019-12-03 03:17:25

I think you could just apply your own filter when the search parameters don't exist:

def index
  @search = Job.search(params[:q])
  @results = @search.result
  @results = @results.where(:your_date => nil) unless params[:q]
  @job = @results.paginate(:per_page => 10, :page => params[:page])
end

Late to the party, but thought I'd suggest an alternate approach in case someone else comes across this.

The answer above works, but its disadvantage is that the default is not added to Ransack's search object, so - if you are using a search form - the default selection is not shown in the form.

The following approach adds the default to the search object and therefore will appear in your search form.

def index
  @search = Job.search(params[:q])
  @search.status_cont = 'Open' unless params[:q] #or whatever, must use Ransack's predicates here
  @results = @search.result
  @job = @results.paginate(:per_page => 10, :page => params[:page])
end

So by default, you want the page to load with records where actual is nil. And later when the user searches you want to go back to how your search was working before.

Give this a try.

def index
   @search = Job.search(params[:q] || Job::DEFAULT_SEARCH_PARAMETER)
   @search.build_condition
   @results = @search.result
   if @results.nil?
        @results=Job.find(:all, :conditions => ["actual = NULL"] )
   end

   @job = @results.paginate(:per_page => 10, :page => params[:page])
end    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!