title: Rails ActiveRecords with own attributes + associated objects' IDs
body: <p>I have a rather simple ActiveRecords associations like such (specifically in Rails 4):</p>
  
  <ul>
  <li>An organization has many users</li>
  <li>A user belongs to an organization</li>
  </ul>
  
  <p>But in terms of ActiveReocord queries, what's an optimal way to construct a query to return an array of Organizations each with its own array of user ids associated with itself? Basically, I'd like to return the following data structure:</p>
  
  <pre><code>#&lt;ActiveRecord::Relation [#&lt;Organization id: 1, name: "org name",.... user_ids: [1,2,3]&gt;, &lt;Organization id: 2...&gt;]&gt;
  </code></pre>
  
  <p>... or to distill it even further in JSON:</p>
  
  <pre><code>[{id: 1, name: 'org name', ... user_ids: [1,2,3]}, {...}]
  </code></pre>
  
  <p>where <code>users</code> is not part of the Organizations table but simply an attribute constructed on the fly by ActiveRecord.</p>
  
  <p>Thanks in advance.</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> After trying a few things out, I came up with something that returned the result in the format I was looking for. But I'm still not sure (nor convinced) if this is the most optimal query:</p>
  
  <pre><code>Organization.joins(:users).select("organizations.*, '[#{User.joins(:organization).pluck(:id).join(',')}]' as user_ids").group('organizations.id')
  </code></pre>
  
  <p>Alternatively, the JBuilder/Rabl approach @<a href="https://stackoverflow.com/users/1081668/kien-thanh">Kien Thanh</a> suggested seem very reasonable and approachable. Is that considered current best practice nowadays for Rails-based API development (the app has the back-end and front-end pieces completely de-coupled)?</p>