简体   繁体   中英

In Ruby on Rails Restful Authentication, UsersController#new, a @user = User.new is used. Is it actually needed?

After

script/generate authenticated user sessions

users_controller.rb is created with

def new
  @user = User.new
end

and the view has this line:

@user.password = @user.password_confirmation = nil

and that's it. Is this actually needed? I mean the form will POST to /users which is by RESTful routing, going to UsersController#create , so the @user created actually is never used. Is it actually needed and why? thanks.


Update: @user is never used again any where else... also, I tried removing those two lines

@user = User.new

and

@user.password = @user.password_confirmation = nil

and I can still use the form to create a new user...

It is needed to render proper form on view. Forms can say if it is just non-saved objects, like here, so form will create post request. If it is a user that was found in DB, then it will automatically create PUT request for update.

<%= form_for @user do |f| %>
  <%#= something %>  
<% end %> 

It will behave differently if you do in your controller User.new, or User.find(id)

In the view it kind of makes sense. Let say user account creation fails - you'll be re-rendering the new view with a different (not new) @user object. I'd probably reset the password and password_confirmation in the action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM