title: Use Postgres Array Column for Rails Many-to-Many Relationship
body: <p>I've been hearing lately that some <code>many-to-many</code> and <code>one-to-many</code> relationships (without additional join data, eg user-membership-group) can be queried <em>significantly</em> faster in Postgres using array columns of id's rather than join tables <a href="https://github.com/tgriesser/bookshelf/issues/363" rel="nofollow">see discussion for Node Postgres ORM</a>. </p>
  
  <p>For a <code>many-to-many</code> relationship, choosing which table (or both) to maintain the relationship arrays would depend on which direction the query goes (users&lt;->groups would need array columns on both tables, users->tag would only require the relationship to be maintained in an array column on the users table only.</p>
  
  <p>Several questions:</p>
  
  <ul>
  <li>Are there any gems (Rails or otherwise) that are using the new Postgres array column to maintain relationships?</li>
  <li>Does anyone have any benchmarks for comparing a simple join table vs array column on a bi-directional and one directional <code>many-to-many</code> relationships? </li>
  <li>To capture the performance improvements with Ruby, very basic functionality would look something like below. Aside from configuration for custom primary keys, method and class names, do you see any obvious improvement to be made from the code below?</li>
  </ul>
  
  <p>```</p>
  
  <pre><code>module ArrayRelationships
  
   def self.included(base)
     base.extend(ClassMethods)
   end
  
   module ClassMethods
     # association must be lower case, pluralized name of associated class
     def array_has_many(association)
      define_method(association) do 
        instance_name = association.singularize
        class_name = instance_name.titleize
        class_name.constantize.where(id: self.send("#{instance_name}_ids"))
      end
     end
   end
   end
  
   class User &lt;&lt; ActiveRecord::Base
     include ArrayRelationships
     array_has_many :tags
   end
  </code></pre>
  
  <p>Of course, the users table would have to have the <code>:tag_ids</code> array field in the database. If we wanted to add the inverse relationship for Tag#users, we would simply add the db field, include ArrayRelationships, and <code>array_has_many :users</code>.</p>