Rails 不能 Marshal.dump 分页数据??

kehao · 2012年03月21日 · 最后由 Rei 回复于 2012年03月21日 · 3620 次阅读

偶尔发现不能 Marshal.dump 分页数据,这怎么回事?现在 will_paginate 和 kaminari 都返回 ActiveRecord::Relation 了

 Marshal.dump Question.where(id:1)
 #=> "\x04\bo:\eActiveRecord::Relation':\v.....

 Marshal.dump Question.where(id:1).page(1)

#TypeError: can't dump anonymous class #<Module:0x00000003ea17f0>
#   from (irb):16:in `dump'
#   from (irb):16
#   from /home/qiu/.rvm/gems/ruby-1.9.3-p0/gems/railties-#3.2.2/lib/rails/commands/console.rb:47:in `start'
#   from /home/qiu/.rvm/gems/ruby-1.9.3-p0/gems/railties-#3.2.2/lib/rails/commands/console.rb:8:in `start'
#   from /home/qiu/.rvm/gems/ruby-1.9.3-p0/gems/railties-#3.2.2/lib/rails/commands.rb:41:in `<top (required)>'
#   from script/rails:6:in `require'
#   from script/rails:6:in `<main>'



Marshal can't dump following objects:

anonymous Class/Module.

objects which related to its system (ex: Dir, File::Stat, IO, File, Socket and so on)

an instance of MatchData, Data, Method, UnboundMethod, Proc, Thread, ThreadGroup, Continuation

objects which defines singleton methods

def get_answers(page)
   Rails.cache.fetch "test1/#{page}" do 
     answers.page(page)
   end
 end



上面的就不能用了,这怎么解决?? active_support/cache.rb @value = Marshal.dump(value)

大家有这种问题么?还是我环境出问题了?

ActiveRecord::Relation 是延迟查询,可以找找有什么方法立即执行

Question.where(id:1).to_a

Question.where(id:1).page(1).to_a

to_a 和 all ,first,last 都可以立即执行,问题是 view 里的 = paginate @targets 用不了了

#3 楼 @Saito to_a 不知道有没有 paginate 要用的 totoal_count 之类的属性

#5 楼 @Rei Array 没有 current_page,include....之类的方法

# Wrap an Array object to make it paginatable
# ==== Options
# * <tt>:limit</tt> - limit
# * <tt>:offset</tt> - offset
# * <tt>:total_count</tt> - total_count
def self.paginate_array(array, options = {})
  PaginatableArray.new array, options
end

https://github.com/amatsuda/kaminari/blob/master/lib/kaminari/models/array_extension.rb

#7 楼 @Rei
my_array_object=Question.where(id:1).page(1).to_a Kaminari.paginate_array(my_array_object).page(params[:page]).per(10) 取出第一页的数据你再分页有什么用? my_array_object=Question.where(id:1).to_a Kaminari.paginate_array(my_array_object).page(params[:page]).per(10) 分页查询又没用

所以这是个疑难问题。

#9 楼 @calebx 缓存 PaginatableArray 对象就行了

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册