I have searched everywhere to try to find an explanation of how this works/what its purpose is, but I cant find anything helpful. I am doing Michael Hartl's tutorial, and my question is mainly about the two actions: 'new' and 'create'. The new action has the following:
def new
@user = User.new
end
In the view corresponding to the 'new' action, there is a form_for helper, where users can type in their attributes and hit submit. As expected, the beginning of the form_for helper looks like this: form_for(@user)
However here is where I am stumped... In the create action, there is the following code:
def create
@user = User.new(user_params)
#user_params is a function we defined which simply returns the permitted params from the user.
What is the purpose of @user = User.new in the 'new' action? What does User.new even accomplish? I am assuming that the instance variable @user is necessary to pass to the form, but in that case, why do we have to redeclare an @user isntance variable in 'create'? Isn't it sufficient to have only @user = User.new(user_params) in our 'create' action? Is the User.new somehow necessary to make the form function properly?
I am mainly just trying to figure out what @user = User.new accomplishes in our 'new' action and its corresponding 'new' view (with the form), and why it is necessary when we have a 'create' action which actually CREATES the object. ANY help is SO GREATLY APPRECIATED. Thank you all for always doing your best to explain. Thank you ahead of time to anyone who answers this.
The new and create are different actions. New is called when you get the new route. Create is called when you post to the new route. So, you have to create the user in new so they're available in the form. You have to create the user with the form contents in create so you can save it to the database.
You can't assume that the request to new will go to the same rails instance as the request to create. It's common to run multiple instances of your app behind a proxy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With