Rails, sessions, and associations.

View blog reactions Written on April 22, 2007 by Chris Heald

Rails has the really nice ability to store an AR model object in the session for easy access. Additionally, it obeys the following rules:

  • If obj.new_record? == true, then any associations on the object will be saved in the session as well.
  • If obj.new_record? == false, then any associations whether association.new_record? == true or false will be nilled before the session is saved, to prevent the session from growing to extreme sizes.

I have an object that is created, things associated with it, saved in the session, previewed, confirmed, and then saved. This works beautifully, because the entire way through, .new_record? == true for the object. However, after saving the object, reloading it from the database, and then adding an association to it, I found that saving the object to the session stripped my association! This was extremely irritating, and it took some sludging through the Rails core code to understand what was going on.

Now what I’m doing is:

  • The saved object is loaded from the DB and saved to the session
  • The new association is created with obj.build_association and then saved to the session
  • On each page load, if the association exists in the session, then it is re-associated with the model.

This seems really ugly and hackish, but it works. If there’s a better way, please let me know what it is.

I’ve been beating my head against the wall on this problem for about four hours now, and it finally hit me.

Leave a Reply

You may use these HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>