# Temporary Model Data

**URL:** <https://www.ruby-forum.com/t/temporary-model-data/55194>\
**Category:** Rails\
**Created:** [March 17, 2006, 7:28pm UTC](https://www.ruby-forum.com/t/temporary-model-data/55194 "2006-03-17T19:28:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![captaffy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f04885/32.png) [@captaffy](https://www.ruby-forum.com/u/captaffy)\
**Post date:** [March 17, 2006, 7:28pm UTC](https://www.ruby-forum.com/t/temporary-model-data/55194/1 "2006-03-17T19:28:53Z")

</div>

# I am trying to optimize some methods in my model so they don’t repeat CPU intensive algorithms every time I call the method in the same request/response cycle. Eg.

# def invitations all\_pgm\_updates.find\_all do |update| update.invited? end end

# I want to do something like:

# def invitations if @invitations.nil? @invitations = all\_pgm\_updates.find\_all do |update| update.invited? end end @invitations end

but isn’t the instance variable, @invitations, going to stick around  
as long as the record is stored in the session? How do I clear it at  
the beginning of every request? Models don’t have access to flash, I  
don’t think, so I need an alternative.

-John

–  
John S.  
Computing Staff - Webmaster  
Kavli Institute for Theoretical Physics  
University of California, Santa Barbara  
removed\_email\_address@domain.invalid  
(805) 893-6307

---

<div class="post-metadata">

**Author:** ![captaffy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f04885/32.png) [@captaffy](https://www.ruby-forum.com/u/captaffy)\
**Post date:** [March 17, 2006, 8:21pm UTC](https://www.ruby-forum.com/t/temporary-model-data/55194/2 "2006-03-17T20:21:09Z")

</div>

try this:

def invitations  
if @@invitations.nil?  
@@invitations = all\_pgm\_updates.find\_all do |update|  
update.invited?  
end  
end  
@@invitations  
end

---

<div class="post-metadata">

**Author:** ![captaffy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f04885/32.png) [@captaffy](https://www.ruby-forum.com/u/captaffy)\
**Post date:** [March 17, 2006, 8:52pm UTC](https://www.ruby-forum.com/t/temporary-model-data/55194/3 "2006-03-17T20:52:52Z")

</div>

Hi John,

So, you’re storing the model instance in the session right? And it’s  
in that model that you want to cache the expensive data, but you  
don’t want the cache to persist between HTTP requests?

The solution is pretty simple: don’t store the model instance in the  
session. Store the model’s ID instead.

in controller:

before\_filter :get\_my\_model, :only =\> [:some\_action]

def get\_my\_model  
if session[:mymodel\_id]  
@mymodel = MyModel.find(session[:mymodel\_id])  
end  
end

def some\_action  
@mymodel.invitations #builds the model’s @invitations cache  
@mymodel.invitations #uses the cached @invitations  
end

## Hope that helps, Trevor

Trevor S.  
[http://somethinglearned.com](http://somethinglearned.com)
