您的位置:首页 > 大数据 > 人工智能

013 把模型对象存入session的危险性

2008-11-17 14:46 162 查看
Be careful when storing a model in a session. It will behave differently than you expect and can easily get out of sync with the database. Instead of storing the model directly in the session, store the id to the model and use that to fetch it from the database.

在session中存储模型的时候要小心了,这样可能会发生许多与你意愿想违背的情况,并且会与数据库中的数据脱节。不要直接将model放到session中,最好存储它的id值,并且用这个id值来获取数据库中存储的对象。



3个action

prepare将User模型的一个对象存入session,然后跳转到show
show将session中的对象显示出来
update将session中的user对象的name属性改为"Foo"(并不存回数据库),然后跳转到show

如果执行update的话,在session里会一直保存这个name="Foo",除非将session清除。
另外,如果在保存user出错时,这个错误信息也会一直存储在session中。

那么正确的做法是:



将模型对象的id存入session中,在每次显示的时候是从session中取出id值,然后到数据库中查找数据。这样就避免了将对象直接存入session中的种种问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  rails session 休闲 model 013