Rails:用户创建命中其他验证

时间:2013-10-08 10:05:20

标签: ruby-on-rails ruby

我有一个带有地址列的常规用户模型。但是当一个人试图用电子邮件和密码注册时,他会收到错误:zip地址和城镇不能为空。您需要注册的只是电子邮件和密码。如何修复用户创建?

用户模型:

class User < ActiveRecord::Base
      attr_accessible :zip, :state, :town, :address, :email, :password, :password_confirmation,

      attr_accessor :password
      validates_confirmation_of :password
      validates :email, presence: true, format: { with: VALID_E_REGEX }, uniqueness: { case_sensitive: false }
      validates :password, presence: true, format:{  with: VALID_P_REGEX }, if: proc{ password_salt.blank? || password_hash.blank? } 
      validates :zip, format: { with: VALID_ZIP_REGEX }
      validates :address, length: { minimum: 5 }
      validates :town, length: { minimum: 4 }
    end

用户控制器:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      redirect_to root_url, :notice => "Signed up!"
    else
      render "new"
    end
  end 
end

错误:

!! #<ActiveRecord::RecordInvalid: Validation failed: Phone number is invalid, Zip is invalid, Address is too short (minimum is 5 characters), Town is too short (minimum is 4 characters)>

3 个答案:

答案 0 :(得分:2)

这取决于你想要的实际行为。

  • 如果您不想验证额外的属性,请按照Vamsi的说法删除验证。

  • 如果要验证额外属性,而不是创建用户对象,可以添加on: :update,如下所示:

    validates :zip, format: { with: VALID_ZIP_REGEX }, on: :update

  • 如果您想要验证额外的属性,但只有在实际输入时,您可以再次添加allow_blank: true(或allow_nil,具体取决于您的需求是):

    validates :zip, format: { with: VALID_ZIP_REGEX }, allow_blank: true

有关验证及其选项的详细信息,请查看the Active Record Validations guide

答案 1 :(得分:1)

如何使验证成为条件。

validates :address, length: { minimum: 5 }, if: :address

答案 2 :(得分:0)

删除模型中不必要的验证。就这么简单......

如果仅在值存在时才使用它,则可以使用validate的allow_nil或allow_blank选项。或者您也可以使用if条件。

class User < ActiveRecord::Base
      attr_accessible :zip, :state, :town, :address, :email, :password, :password_confirmation,

      attr_accessor :password
      validates_confirmation_of :password
      validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
      validates :password, presence: true, format:{  with: VALID_PASSWORD_REGEX }, if: proc{ password_salt.blank? || password_hash.blank? }
      validates :zip, format: { with: VALID_ZIP_REGEX }, allow_blank: true
      validates :address, length: { minimum: 5 }, allow_blank: true
      validates :town, length: { minimum: 4 }, allow_blank: true
    end