title: Define custom validator by ActiveRecord
body: <p>How can define custom validator that permits first name or last name to be null but not both</p>
  
  <p>My Profile class:</p>
  
  <pre><code>class Profile &lt; ActiveRecord::Base
       belongs_to :user
  
       validates :first_name, allow_nil: true
       validates :last_name, allow_nil: true
  
       validate :first_xor_last
  
  
      def first_xor_last
       if (first_name.nil? and last_name.nil?)
          errors[:base] &lt;&lt; ("Specify a first or a last.")
        end
      end
  </code></pre>
  
  <p>I tries create by self first_xor_last function but does not work.</p>
  
  <p>I recieve this rspec test:</p>
  
  <pre><code>context "rq11" do
         context "Validators:" do
           it "does not allow a User without a username" do
             expect(User.new(:username=&gt; "")).to_not be_valid
           end
           it "does not allow a Profile with a null first and last name" do
             profile = Profile.new(:first_name=&gt;nil, :last_name=&gt;nil, :gender=&gt;"male")
             expect(Profile.new(:first_name=&gt;nil, :last_name=&gt;nil, :gender=&gt;"male")).to_not be_valid
           end
           it "does not allow a Profile with a gender other than male or female " do
             expect(Profile.new(:first_name=&gt;"first", :last_name=&gt;"last", :gender=&gt;"neutral")).to_not be_valid
           end
           it "does not allow a boy named Sue" do
             expect(Profile.new(:first_name=&gt;"Sue", :last_name=&gt;"last", :gender=&gt;"male")).to_not be_valid
           end
         end
       end
  </code></pre>
  
  <p>I should pass it.</p>
  
  <p>Thanks, Michael.</p>