Storing Objects in a Session in Rails

后端 未结 4 1154
一个人的身影
一个人的身影 2020-12-01 08:27

I have always been taught that storing objects in a session was a bad idea. Instead IDs should be stored that retrieve the record when needed.

However, I have an ap

4条回答
  •  情话喂你
    2020-12-01 09:06

    The main reason not to store objects in the session is that if the object structure changes, you will get an exception. Consider the following:

    class Foo
      attr_accessor :bar
    end
    
    class Bar
    end
    
    foo = Foo.new
    foo.bar = Bar.new
    put_in_session(foo)
    

    Then, in a subsequent release of the project, you change Bar's name. You reboot the server, and try to grab foo out of the session. When it tries to deserialize, it fails to find Bar and explodes.

    It might seem like it would be easy to avoid this pitfall, but in practice, I've seen it bite a number of people. This is just because serializing an object can sometimes take more along with it than is immediately apparent (this sort of thing is supposed to be transparent) and unless you have rigorous rules about this, things will tend to get flummoxed up.

    The reason it's normally frowned upon is that it's extremely common for this to bite people in ActiveRecord, since it's quite common for the structure of your app to shift over time, and sessions can be deserialized a week or longer after they were originally created.

    If you understand all that and are willing to put in the energy to be sure that your model does not change and is not serializing anything extra, you're probably fine. But be careful :)

提交回复
热议问题