title: Rails self-referential has_many through with custom naming of join table
body: <p>I have some troubles wrapping my head around the following situation.. </p>
  
  <p>I am trying to create a tree structure, where I will be able to give custom names to connections between nodes.. </p>
  
  <p>So I want to have Node and Relation models. Each </p>
  
  <pre><code>Node 
   has_many :relations
  </code></pre>
  
  <p>Each</p>
  
  <pre><code>Relation 
   has_many :nodes
  </code></pre>
  
  <p>Node can be either a parent or a child.. So far everything was easy and there are tons of examples that show how to make a self-referential has_many table... The problem is that I want  to be able to give names to relations, so that I can do something like:</p>
  
  <pre><code>relation1 = node1.relations.create(:name =&gt; "relation_name", :child =&gt; node2)
  </code></pre>
  
  <p>and in result get something like:</p>
  
  <pre><code>relation1.name == "relation_name"
  relation1.parent == node1
  relation1.child == node2
  </code></pre>
  
  <p>All the creations are happening within the model, this activity is not really exposed to user, if that matters.
  Thanks!</p>
  
  <p>EDIT2: 
  Here is how it works now:</p>
  
  <pre><code>class Node &lt; ActiveRecord::Base
    belongs_to :sentence
  
    has_one :parent_relation, :foreign_key =&gt; "child_id", :class_name =&gt; "Relation"
    has_many :child_relations, :foreign_key =&gt; "parent_id", :class_name =&gt; "Relation"
  
    has_one :parent, :through =&gt; :parent_relation
    has_many :children,  :through =&gt; :child_relations, :source =&gt; :child
  
    has_many :relations, :foreign_key =&gt; "child_id"
    has_many :relations, :foreign_key =&gt; "parent_id"
  
  class Relation &lt; ActiveRecord::Base
  
    has_many :videos, :as =&gt; :videoable, :dependent =&gt; :destroy
    has_many :phrases, :through =&gt; :videos
  
    belongs_to :parent, :class_name =&gt; "Node"#, :inverse_of =&gt; :parent_relation
    belongs_to :child, :class_name =&gt; "Node"#, :inverse_of =&gt; :child_relation
  </code></pre>