Rails项目中用上了Ferret分布,全文检索后,发现will_paginate的分页用不上了,于是google ,再配合实际情况,山寨了一个适合自己的版本。
参考了这篇文章:
http://opensoul.org/2007/8/17/acts_as_ferret-will_paginate
model
#全文检索方法
def self.full_text_search(q, options = {})
return nil if q.nil? or q==""
default_options = {:limit => 10, :page => 1}
options = default_options.merge options
# get the offset based on what page we're on
options[:offset] = options[:limit] * (options.delete(:page).to_i-1)
results = Page.find_by_contents(q, options)
end
戏肉来了,在application.rb写了一个公用的分页
#全文检索分页方法
def pages_for(result,options = {})
page, per_page, total = (options[:page] || 1),(options[:per_page] || 30),(result.total_hits || 0)
page_total = page * per_page
index = (page.to_i - 1) * per_page
pager = WillPaginate::Collection.new(page, per_page, page_total)
returning WillPaginate::Collection.new(page, per_page, total) do |pager|
pager.replace result[index,per_page]
end
end
在controller中如下使用
results = Page.full_text_search @q
@pages = pages_for(results,:page => 1)
当然山寨的东西,质量不敢保证,不过不用担心,会有售后服务的,只是先写下这个思路和初步的实现(怕忘记了),以后继续使用,会慢慢地完善。