eeeeeean eeeeeean - 10 months ago 51
Ruby Question

What does render do with instance variables?

When I use a scaffold to generate a Foo model/controller, my controller has a default create action that will

render :new
returns false.

What happens to my @foo object when I
render :new

My stock new.html.erb view refers to
, which makes me think that it reuses the @foo from my create action (rather than create a new object with
@foo =
again in the new method). Is this not the case?

I'm worrying about this because I want to reuse this convention in a new namespaced controller (everything else appearing equal), but I get nil for @foo when
render :new
happens. It appears it's neither reusing the Foo object, nor creating a new one. So I'm trying to understand render better.


render doesn't call the action new, it just processes the file new.html.erb (or whatever) and sends it to the browser. The @foo instance variable created in your create action is used when rendering that template, that's why, if the record fails to save, the when the form is rendered the user's information is still present in the form fields (assuming the form is set up correctly).

If you want to start a whole new request with a fresh @foo instance variable, you can redirect_to :new instead of rendering, or just manually set @foo = before the call to render.

If you have a 'new namespaced controller', that's (self-evidently) not the same controller. It's not clear exactly what you're doing from the question, but if you're setting @new in one controller and then trying to access it from another controller... that's never going to work.