新手问题 rails3 敏捷中的 迭代 F1

yangman_wenzhu · 2012年12月12日 · 最后由 yangman_wenzhu 回复于 2012年12月13日 · 2671 次阅读

在这章迭代里,主要是新建用户表单,没用插件,代码如下: 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

在提交表单时 会提示

这个错误 可是我填写密码和确认密码 并且他们相等 求各位闲暇时看下 谢谢了

你代码中有些是 password_confirmation 有些是 password_confirmaton?

#1 楼 @HKB 哦 谢谢啊 是这里的问题
那我请教下 看那写代码 时间长就会很细心呢?

#2 楼 @yangman_wenzhu 细心是靠自己培养的,不是看代码看出来的。小错误是难免的,主要是能看到出错信息就马上知道错在哪并改正。多多练习就好,错多了自然知道错在哪。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号