title: Horizontal database scaling in Ruby on Rails
body: <p>I have a Ruby on Rails app with a PostgreSQL database which has this structure:</p>
  
  <pre><code>class A &lt; ActiveRecord::Base
     has_many :B
  end
  class B &lt; ActiveRecord::Base
      has_many :C
  end
  class C &lt; ActiveRecord::Base
      attr_accessible :x, :y :z
  end
  </code></pre>
  
  <p>The are only a few A's, and they grow slowly (say 5 a month). Each A has thousands of B's, and each B has tens of thousands of C's (so each A has millions of C's).</p>
  
  <p>A's are independent and B's and C's from different A's will never be needed together (i.e. in the same query).</p>
  
  <p>My problem is that now that I have only a couple of A's, ActiveRecord queries take pretty long. When the table for C has tens of millions of rows, queries will take forever.</p>
  
  <p>I am thinking about scaling the database horizontally (i.e a table for A's, one table of B's and one table of C's for each A). But I don't know how to do it. It is a kind of sharding i guess, but I can't figure out how to create DB tables dynamically and use ActiveRecord to access the data if the table depends on which A im working with.</p>
  
  <p>Thank you very much.</p>