title: Rails model validation which check if already exists object with some property
body: <p>I have following model:</p>
  
  <pre><code>class TestModel &lt; ActiveRecord::Base
    enum some_column: [:prop1, :prop2, :prop3]
  end
  </code></pre>
  
  <p>I want to ensure i will always have maximum one object with prop1 column value in database, while i can have multiple numbers of object with prop2 or prop3 objects or none of them. It would be great if it could be a model validation. I tried this way but not sure if this is good practice for a rails app:</p>
  
  <pre><code>      if ((id.nil? and TestModel.where(some_column: 'prop1')) or (TestModel.where(some_column: 'prop1').where.not(id: id)))
  </code></pre>
  
  <p>I tried with left side to cover create action, with right side to cover update. Is there any rails way to do this?</p>
  
  <p>Thanks</p>
  
  <p><strong>UPDATED</strong></p>
  
  <p>This is solution for my problem</p>
  
  <pre><code>def only_one_prop1_record
    if(some_column == 'prop1')
      if new_record? #if create action
        if TestModel.where(some_column: 'prop1').any?
          errors.add(:base, 'You can only have one prop1 record')
        end
      elsif persisted? #if update action
        if TestModel.where(some_column: 'prop1').where.not(id: id).any?
          errors.add(:base, 'You can only have one prop1 record')
        end
      end
    end
  end
  </code></pre>
  
  <p>And call validation like this: <code>validate :only_one_prop1_record</code></p>