title: Data model design to express logical criteria
body: <p>I'm having some trouble coming up with the most efficient data model for storing logical criteria. The criteria can be as follows:</p>
  
  <ul>
  <li>Field = Value</li>
  <li>Field != Value</li>
  <li>Field1 = Value1 AND Field2 = Value2</li>
  <li>Field1 = Value1 OR Field2 = Value2</li>
  </ul>
  
  <p>But can also be nested as so:</p>
  
  <ul>
  <li>(Field1 = Value1 OR Field2 = Value2) AND Field3 = Value3</li>
  </ul>
  
  <p>The nesting can be infinitely deep. </p>
  
  <p>I started with a model like this:</p>
  
  <pre><code>Criterion
    Field Name
    Comparison Operator
    Comparison Value
  </code></pre>
  
  <p>This allows me to express simple criteria such as 'Field = Value'. </p>
  
  <p>How should I go about chaining the <code>Criterion</code> together using AND/OR statements and what is the best way to handle the nesting?</p>
  
  <p>FYI (might add more context) - this is for a Rails/Mongoid project. I have a <code>Document</code> which <code>embeds_many :criteria</code>. I need to be able to call <code>Document.criteria_string</code> and have the document iterate over all the criteria and assemple it into a single statement accounting for the nesting, chaining and positioning of the criteria.</p>
  
  <p>Thanks!</p>