[英]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 users_controller.rb
是用。创建的
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. 我的意思是表单将POST到/users
,这是通过RESTful路由,转到UsersController#create
@user
,所以@user
创建实际上从未使用过。 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 = 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. 如果是在DB中找到的用户,则它将自动创建PUT请求以进行更新。
<%= form_for @user do |f| %>
<%#= something %>
<% end %>
It will behave differently if you do in your controller User.new, or User.find(id) 如果你在控制器User.new或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. 假设用户帐户创建失败 - 您将使用不同的(非新的) @user
对象重新呈现new
视图。 I'd probably reset the password and password_confirmation in the action. 我可能会在操作中重置密码和password_confirmation。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.