the bit of code I see everywhere to clear stale sessions is some
variant of this:
class SessionCleanup
def self.cleanup
CGI::Session::ActiveRecordStore::Session.destroy_all(
['updated_at < ?',
$session_cleanup_interval_in_mins.minutes.ago]
)
end
end
"Destroys the records matching conditions by instantiating each record
and calling the destroy method. This means at least 2*N database
queries to destroy N records, so avoid destroy_all if you are deleting
many records. If you want to simply delete records without worrying
about dependent associations or callbacks, use the much faster
delete_all method instead."
So, again, a best practice question:
Since I don't think there are dependent associations that would need
to be destroyed from the session, why not call the delete_all method
instead?
The solution does depend on the particular situation. It is not clear to me what you are trying to
achieve. Is it stale sessions from anonymous visits or ones from account logins that forgot to
logout? Perhaps both.
In the first case, a cron job that runs say once per day will complete in like a second or two. I
don't see a performance issue here.
For the second case I refer you to a previous post.
I often employ both methods because each addresses a different area.
You are correct, #delete_all is more efficient than using #destroy_all. Provided that it is
supported in the context of ActiveRecordStore::Session. I have yet to use it so can't say for sure.
If you're using rails 2.0, and the cookie-based session store, you don't have to clear out stale sessions. If you are running an earlier version with AR store, you can run a cron job that just runs a mysql command to delete records older than a specified age. No reason to get Rails involved. If you're really worried about performance, you can nice the command.
Thanks for the replies and sorry for my delay in responding (other
matters arose).
I am still on rails 1.2.5, so I cant take advantage of 2.0 goodies
yet.
I like the idea of going directly to the the DB with SQL rather than
invoking rails from a cron job.
For the moment I am using the code I posted above and calling it from
a freq invoked action... works well for now, but I'll change in
anticipation of heavier traffic down the road.