orcman
orcman

Reputation: 35

Why does the object id change following failed validations in a rails controller?

I've generated a simple rails app using scaffolding. In the user model I have added a validation for the presence of name. I am using debug(@user.object_id) and showing at the top of my user edit page in edit.html.erb

I've purposefully left the name blank and tried to submit the form. The usual errors are rendered but every time I submit the form, the @user's object id changes. Could someone please explain why the object_id is changing? My assumption was that the @user is still the same object (since we're in the same page, just adding errors and re-rendering the edit.html.erb on failed update)

Upvotes: 2

Views: 56

Answers (2)

Igor Drozdov
Igor Drozdov

Reputation: 15045

You probably confused by the fact, that render :edit in the update method just renders the edit template, but doesn't redirect to the edit page - that's right.

But, actually this is what happens in your scenario:

  • edit page is visited, @user assigned in the edit method of UsersController
  • form is submitted, update action is called and found @user is assigned in the update method and renders edit template

Thus, on submitting a form different method is called and the state changes

Upvotes: 1

Peter Zhu
Peter Zhu

Reputation: 461

No, your assumption is not correct. HTTP calls are stateless, meaning that state does not persist between calls (i.e. every call is independent of each other). Every time your form is submitted, a new object is created and assigned to the variable @user. Since a new (and different) object is created during each call, their object_ids will be different.

Upvotes: 1

Related Questions