在未更改URL的情况下,Ruby on Rails渲染注册失败



大家好,我是ruby on rails的新手,我只是想问如何渲染失败的注册尝试w/o更改URL和验证?

新用户注册表单-

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 %>

相关内容

  • 没有找到相关文章

最新更新