title: rails sql find models related to self with attribute difference greater than threshold
body: <p>I have a <code>Person</code> model in rails that is related to itself:</p>
  
  <pre class="lang-rb prettyprint-override"><code>class Person &lt; ApplicationRecord
    has_many :children,
      class_name: "Person",
      foreign_key: :person_id
  
    belongs_to :mother,
      class_name: "Person",
      foreign_key: :person_id
  end
  </code></pre>
  
  <p>People also have an <code>age</code> attribute representing their ages in years. I would like an ActiveRecord or SQL query to find all people with child-to-mother age discrepancies that are greater than or equal to 50 years.</p>
  
  <p>(The model name here is not what I'm truly using in my app. I renamed it to simplify the problem description. However, for my actual query I will need to know if the <em>absolute value</em> of the age difference is greater than or equal to 50 years. Obviously children can't be older than their mothers so the analogy doesn't hold there.)</p>
  
  <p>I have tried the following and several variants, which are all crashing:</p>
  
  <pre><code>    Person
        .includes(:mother)
        .where("ABS(persons.age - (SELECT age FROM persons WHERE (id = persons.person_id))) &gt;= 50")
  </code></pre>
  
  <p>This one in particular results with a hint:</p>
  
  <p><code>HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.</code></p>
  
  <p>At first I thought that maybe the latest SQL querie's <code>where</code> clause was returning some sort of list of ages rather than just the mother's age, so I tried subscripting with a <code>[1]</code> after it to get the first element of (what should be) a single element array (if my hypothesis was correct). It was not correct - the SQL error then updated to let me know I couldn't subscript something that wasn't an array.</p>
  
  <p>I'm looking for the simplest solution. Any help is appreciated. Thanks!</p>