title: Ruby on Rails API: computed attribute pattern best practice
body: <p>I would like to know the best practice when I need a computed attribute that require a call to the database.</p>
  <p>If I have a <code>Parent</code> that has many <code>Child</code>, how would I render a <code>children_count</code> attribute in <code>ParentController#index</code> as I don't want to render the children, just the count? what's the best way to do it?</p>
  <p>Thank you!</p>
  <p>Model:</p>
  <pre><code>class Parent &lt; ApplicationRecord
    has_many :children
  
    def children_count
      children.count # Wouldn't it ask the database when I call this method?
    end
  end
  </code></pre>
  <p>Controller:</p>
  <pre><code>class ParentsController &lt; ApplicationController
    def index
      parents = Parent.all
  
      render json: parents, only: %i[attr1, attr2] # How do I pass children_count?
    end
  end
  </code></pre>