0

following the RailsTutorial book (http://ruby.railstutorial.org/chapters/sign-up#sec-signup_form)

we have the following snippet:

def new
 @user = User.new
end

def create
 @user = User.new(user_params)
 ....
end

why do we need to recreate the model, if the user goes to /users/new def new is called and @user variable is initialzed, but on post request (def create), User.new is recalled, why is this? if we are going to create a new user model on create then why create it in def new?

4

2 回答 2

1

Because every request will generate a new instance of controller. #new has an instance, and #create has another one, and another hit on #new create another new one. These controllers instances are different, and their instance variable @user is different.

于 2013-09-27T04:38:06.510 回答
1

new doesn't save the model to the database. It just instantiates a temporary instance.

So when the action new calls User.new, it creates a tremporary variable with no values in it - which it then passes to the view to help display the form... and then that temporary variable gets thrown away.

When you hit the submit button on the form, the form params gets sent to the create action in the application which then calls User.new with the params to instantiate a fresh model - with the values passed in the form.

Your create method will usually then call save on the model which will save the data into the database.

于 2013-09-27T05:21:45.573 回答