我正在尝试将我的rails gem从2.3.2升级到2.3.11。但是,我在使用will_paginate 2.3.15时遇到了一些问题并将json渲染回来。
module WillPaginateHelpers
WillPaginate::Collection.class_eval do
alias :to_json_without_paginate :to_json
def to_json(options = {})
hash = { :current_page => current_page,
:per_page => per_page,
:total_entries => total_entries,
:total_pages => total_pages,
:items => to_a
}
hash.to_json(options)
end
end
end
以前,上面的代码可以使用:
@products = Product.paginate(:page => 1, :per_page => 20)
render :json => @products
但是,对于rails 2.3.11,它会出现错误“对象引用本身”,除非我需要这样编码:render :json => @products.to_json
。
如何解决这个问题? render :json => @products
发生了什么?
答案 0 :(得分:4)
我已将此添加到初始化程序中:
class WillPaginate::Collection
def as_json options={}
{
:total_entries => self.total_entries,
:current_page => self.current_page,
:total_pages => self.total_pages,
:per_page => self.per_page,
:items => super
}
end
end