Politics, Programming and Possibilities
12 May
I had a doozy of a bug today: an “Album” model has_many “Track” objects, but calling album.tracks.clear was not deleting or destroying the associated tracks in spite of my having explicitly set :dependent => :destroy on the has_many association.
As it turns out, my object (the album) was being stored in the session, and therefore the associated tracks were also in the session. When I called album.tracks.clear, the foreign keys were nullified instead of the rows destroyed.
The solution: store album ids in the session instead of the whole object, and do an Album.find(session[:album_id]).
2 Responses for "Rails Gotcha: Associations Stored in the Session"
I find it to be dangerous to store objects in sessions. I always use ids.
An extreme case of why not store objects in a session:
your login stores the user’s object in a session.
the admin upgrades/downgrades a logged in user’s permissions.
the logged in user will be using their old permissions, unless they log back in or code is explicitly written to observe changes to the record.
Thanks for the tip, Duane. Sometimes I would wonder whether to store an object in the session hash or just the id to the object, and your example cements it for me.
Leave a reply