Mongoid, will_paginate, sorting does not work with Mongolian DSL criteria

According to reading mongoid on github, I can make fantastic requests like Person.select (: first_name ,: last_name) .where (: title => "Sir"). Skip (10) .limit (10) .paginate

I tried this in conjunction with will_paginate (3.0.pre2)

@companies = Company.paginate(:per_page=>5, :page=>params[:page], :sort => [sort_column, sort_direction])

---> works great

@companies = Company.all.paginate(:per_page=>5, :page=>params[:page], :sort => [sort_column, sort_direction])

---> sorting no longer works

I tried

@companies = Company.where(:name=>/^#{params[:search]}/).paginate( :per_page=>5, :page=>params[:page], :sort => [sort_column, sort_direction])

-> does not work

then

@companies = Company.paginate(:conditions=>{:name=>/^#{params[:search]}/}, :per_page=>5, :page=>params[:page], :sort => [sort_column, sort_direction])

---> works

But I think that the search functions should not be in the controller in the model!

+3
source share
1 answer

Decision:

Do not use sorting in paginate, use instead order_by(). For instance:

company model:

def self.search(search)
  if !search.blank?
   where(:name => /^#{search}/)
  else
   all
  end
end

():

 @companies = Company.search(params[:search]).order_by([sort_column, sort_direction]).paginate(:per_page=>5, :page=>params[:page])
+6

Source: https://habr.com/ru/post/1780231/


All Articles