开发者

Rails 3.1.rc5 custom validator: allow_nil doesn't work, :if => lambda{} works

开发者 https://www.devze.com 2023-03-31 02:00 出处:网络
I write a custom validator for AR, named InvitationValidator So this piece of code: User < ActiveRecord::Base

I write a custom validator for AR, named InvitationValidator So this piece of code:

User < ActiveRecord::Base
...
  attr_accessor :invitation
  attr_accessible :invitation
  validates :invitation, :invitation => true, :allow_nil => true
end

doesn't allow nil invitation to get th开发者_高级运维rough

And this one does allow nil value to get through:

User < ActiveRecord::Base
...
  attr_accessor :invitation
  attr_accessible :invitation
  validates :invitation, :invitation => true, if => lambda {|u| u.invitation.present?}
end

My validator looks like this:

class InvitationValidator < ActiveModel::Validator
  def validate(record)
    record.errors.add(:invitation, :invalid) unless Invitation.where(:code => record.invitation).count > 0
  end
end

Why setting allow_nil doesn't help? (I'm using devise by the way)


The value could be "" (not nil). :if => lambda works fine because "".present? == false.

Try :allow_blank instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消