Tuesday, June 26, 2007

如何在Rails Session中存取模型对象object


当在controller中存放某个对象(比如是一个:对象)到Session中时,应用程序会报错,并抛出一个500错误,而不是Rails的错误(在存的时候不会错,但读取就报错,因为不能正常反序列化对象)。这需要在application.rb(contollers folder)中require此对象的class,重启Rails服务器进程重新打开浏览器即可。
另外也可以在controller中加上model声明,这样Rails就会预先加载对应的模型类,在反序列化的时候就能知道他们的类型定义。
class ApplicationController < ActionController::Base
model :user
end


在Rails SESSION中存放对象是有限制的,一般在session中的对象是要求可序列化的(用Ruby Marshal library),见programming ruby 2nd中说明:
Module Marshal
The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted.
对于不可序列化对象如I/O对象就能放入SESSION中。

1 comment :

Biby Cletus said...

Hi, i just surfed in searching for interesting blogs on Spirituality, you have a cool blog. Do keep up the good work. I'll be back even though i live far from where you live. its nice to be able to see what people from across the world thinks.

Warm Regards from the Other Side of the Moon.

On a related note perhaps you might find the following link interesting. Its propossing a theory and i'll like to hear your take on the subject via comments. See ya...

Was
Jesus an Essenes ?


Bibby

Kerala, India