Reputation: 5251
I was reading this article about new, create, and forms and there are a few parts on User creation process that I don't fully understand.
I want to create User with basic attributes: name
, email
. On routes I have resources :user
, and:
users_controller.rb
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to @user, alert: "User created successfully."
else
redirect_to new_user_path, alert: "Error creating user."
end
end
views/users/new.html.erb
<%= form_for(@user) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
...
on new
instance variable @user
is created: @user = User.new
. Now, I understand that this new
@user
is the same @user
used in <%= form_for(@user) do |f| %>
(right?). I don't understand when @user
in create
method comes in.
There is no create.html.erb
because create is really a POST request. Does that mean @user
on create
gets passed on from new
's @user
? When does create
method gets activated? Why do I need to declare @user = User.new
in both new
and create
? When does create
's @user
gets saved (in other word, what action saves this new user instance)?
I apologize for the many questions. There are a lot of behind-the-scenes that I don't know. If I have to sum it up, what I want to understand is:
How does form_for
work with new
and create
to create user and what does form_for
do with each new
's@user
and create
's @user
?
Upvotes: 0
Views: 44
Reputation: 84142
Rails copies controller instance variables to whatever view is rendered: when the new
view is rendered, the @user
variable has the same value as @user
in the controller.
The create
method is called when the form is submitted (when the user clicks submit). It creates a new instance of User
, using the submitted parameters. Every http request is processed by a new instance of the appropriate controller, so this @user
is unrelated to the instance from the new action. Nothing happens in terms of the database until the call to @user.save
Upvotes: 0
Reputation: 9700
You are correct. when you POST
to the user route, it re-renders the new
method, unless you redirect or render another method. So declaring the instance variable @user
in the create method allows this to be passed back to the new
template. If you didn't specify this instance variable, Rails would complain that the form param can't be blank since @user
isn't set (Since the method rendering the template is create
not new
).
Upvotes: 1