Topic: has_many association and session

I have parent ActiveRecord object and a set of child ActiveRecord objects. I use has_many/belongs_to association between them (parent has many children). When I store parent object in session all its children is stored in session too. This is unacceptable - I wanted it to store just parent and make SQL calls for each children retrieval.

Here are my classes:
1) Parent:

class Parent < ActiveRecord::Base
  has_many :children
end

2) Child:
class Child < ActiveRecord::Base
  belongs_to :parent
end

Code that I use to store parent in session:
p = Parent.find(1)
session[:parent] = p
c = p.children

After that I've got session with all children of 1st parent!

Shoot goes down the hill

Re: has_many association and session

Simply put, complex objects (like models) should not be stored in a session. This is partly due to the problem you are experiencing, but there are other problems down the road you will come across.

Instead you should just store the id of the model in the session. You can create a method to fetch the parent from the database whenever you need access to it. I can provide some code if you need it.

Railscasts - Free Ruby on Rails Screencasts

Re: has_many association and session

Thank you for your answer, ryanb.

It seems, that I'm going to have to revise my application architecture. Now I have application written completely on Delphi/COM+/ASP+VBScript. It utilizes similar concepts of data persistence - just like Rails/ActiveRecord. The application stores tree of objects in session (in memory space of IIS). I was confused to know that Rails application stores session data on hard drive (<appRoot>/tmp/sessions/). This could be a serious performance issue. Is there any way to solve this?

Thank you.

Shoot goes down the hill

Re: has_many association and session

You can store the sessions in the database using ActiveRecord Store. I forgot the details of enabling it off the top of my head, but I can probably track down some links if you need them.

Railscasts - Free Ruby on Rails Screencasts