Topic: Copying a session object to another object

I am getting wierdness when I pass the session user
to another class for initialization. 

Basically, if I call save, then remove, then save
again (through sequential controller actions)...
it fails to save (resave).

AND it looks like the @user is nil on that third call.
I get the feeling I'm referencing an object that gets
blown away some how.

Controller Code

my_favorites = Favorite.new(session['user'])
flash[:notice] = my_favorites.save(params[:id])

Favorite (or least favorite at the moment) Class
class Favorite
 
  def initialize (user)
    @user = user
  end

  def save (id)
    if !Topic.exists?(id)
      "Unable to find that topic"
    else topic = Topic.find(id)
      if !@user.topics.include?(topic)
        @user.topics << topic
        topic.title + " was successfully saved."
      else
        "Topic already saved!"
      end
    end
  end


  def remove (id)
    if !Topic.exists?(id)
      "Unable to find that topic"
    else topic = Topic.find(id)
      topic.users.delete @user  #ignore remove if it's already gone
      topic.title + ' was successfully removed.'
    end
  end

Re: Copying a session object to another object

Two things I'd try:

first, change the following:
   def initialize (user)
     @user = user
   end
to:
   def initialize (user)
     @user = user.dup
   end

@user = user doesn't copy the object - it just references it.  But user.dup makes a brand new User object with the same values inside.

Second, (if the first doesn't solve anything), start putting debug statements through your code.  For the most drastic (and easiest) debugging just place:
  raise user.to_yaml
somewhere in the file and move it around to see different results.

Re: Copying a session object to another object

I've been reaing up the Assiciations documentation and I'm starting to think it might have something to do with caching... but I wouldn't think rails would cache objects _between_ requests.  Going to try using !@user.topics(true).include?(topic)

Re: Copying a session object to another object

Yep that's it... I was referencing the session object which is being persisted.
And the topics in that session were being cached.  For some reason, even when
I duped the user object it still cached the topics between requests.

I guess I really don't understand what's persistent on the the server in a session.
My assumption was that only the session, cookies, params, and request headers were
being passed and a fresh instance of the controller and models were being created
with each request.  Is that the case?

Anyway, I use topics(true) and it works just fine. 

Thanks for the help & happy holidays