# Instance variables don't persist between actions?

**URL:** <https://www.ruby-forum.com/t/instance-variables-dont-persist-between-actions/51234>\
**Category:** Rails\
**Created:** [December 28, 2005, 5:41pm UTC](https://www.ruby-forum.com/t/instance-variables-dont-persist-between-actions/51234 "2005-12-28T17:41:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Horacio\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/97f17d/32.png) [@Horacio\_S](https://www.ruby-forum.com/u/Horacio_S)\
**Post date:** [December 28, 2005, 5:41pm UTC](https://www.ruby-forum.com/t/instance-variables-dont-persist-between-actions/51234/1 "2005-12-28T17:41:48Z")

</div>

Following a simple example of the Rails book and using scaffolding I got  
a  
simple application to manage a user database.

the controller is like:

def new  
@user = User.new  
@text = “Hello World”  
end

def create  
@user = User.new(params[:user])  
if @user.save  
flash[:notice] = ‘User was successfully created.’  
redirect\_to :action =\> ‘list’  
else  
render :action =\> ‘new’  
end  
end

Note the @text var I create on the new action… The view is the scaffold  
generated one with a little addition at the end to print the @text  
instance  
var I create in the “new” action.

very simple stuff and it works.

If I add validation to the model like “validates\_presence\_of :name”  
and  
press the create button without filling the name field in the form the  
‘new’  
action is rendered with the error box at the top indicating error (this  
is  
ok) but the @text var dissappears. Making some tests I find that @text  
is  
nil when this page is rendered and there are error\_messages\_for user.

If I want the @text var to be displayed in the form when creating a new  
user  
and when there are errors, I have to create that var in both actions  
“new”  
and “create” . I think this is a violation of the DRY principle.

Am I doing something wrong??

regards,  
Horacio

---

<div class="post-metadata">

**Author:** ![Horacio\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/97f17d/32.png) [@Horacio\_S](https://www.ruby-forum.com/u/Horacio_S)\
**Post date:** [December 28, 2005, 6:00pm UTC](https://www.ruby-forum.com/t/instance-variables-dont-persist-between-actions/51234/2 "2005-12-28T18:00:20Z")

</div>

When you hit the create button on your form, the create action is  
called, not the new action. When you get an error on your save, the  
new form is rendered, but the new action isn’t called so the @test  
won’t be set.

You can do “new” before you do your render of new as one workaround.

Chris Nolan.ca  
[http://kekova.ca/](http://kekova.ca/)
