大家好,我是 ruby on rails 的新手,我只想问一下如何在不更改 URL 和验证的情况下呈现失败的注册尝试?
问问题
25 次
1 回答
0
注册新用户的表格-
app/views/users/new.html.erb
<h2>Sign up</h2>
<% form_for(@user) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation, "Confirmation" %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
将 @user 变量添加到新操作 -
app/controllers/users_controller.rb
class UsersController < ApplicationController
.
.
.
def new
@user = User.new
@title = "Sign up"
end
end
可以处理注册失败(但不成功)的创建操作-
app/controllers/users_controller.rb
class UsersController < ApplicationController
.
.
.
def create
@user = User.new(params[:user])
if @user.save
# Handle a successful save.
else
@title = "Sign up"
render 'new'
end
end
end
将错误消息显示添加到注册表单的代码-
app/views/users/new.html.erb
<h2>Sign up</h2>
<% form_for(@user) do |f| %>
<%= f.error_messages %>
.
.
.
<% end %>
于 2013-01-21T12:43:11.077 回答