在这章迭代里,主要是新建用户表单,没用插件,代码如下:
user.erb
class User < ActiveRecord::Base
#这里的password、password_confirmation是虚拟属性
attr_accessor :password_confirmaton
validates_confirmation_of :password
end
users_controller.rb
class UsersController < ApplicationController
def create
p "------#{params[:user][:password]}----#{params[:user][:password_confirmaton]}--------"
@user = User.new(params[:user])
respond_to do |format|
if @user.save
flash[:notice] = "User #{@user.name} was successfully created. "
format.html { redirect_to(:action => "index") }
else
format.html { render :action => "new" }
end
end
end
end
users/new.html.erb
<h1>New user</h1>
<% form_for(@user) do |f| %>
<%= f.error_messages %>
<fieldset>
<legend>Enter User Details</legend>
<div>
<%= f.label :user_password, 'Password' %><br />
<%= f.password_field :password, :size => 40 %>
</div>
<div>
<%= f.label :user_password_confirmaton, 'Confirm' %><br />
<%= f.password_field :password_confirmaton, :size => 40 %>
</div>
<div>
<%= f.submit 'Add User', :class => "submit" %>
</div>
</fieldset>
<% end %>
<%= link_to 'Back', users_path %>
保存新用户时确认密码不填或者和密码不一致 表单都会保存成功 但是自己加的验证:
attr_accessor :password, :password_confirmaton
validates_presence_of :password_confirmation, :if => :password_changed?
validates_confirmation_of :password
def password_changed?
errors.add(:password_confirmation, " no match password ") if password_confirmation != password
end
在提交表单时 会提示
这个错误 可是我填写密码和确认密码 并且他们相等 求各位闲暇时看下 谢谢了