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.
精彩评论