Rails self-referential has_many through custom join table naming

I have some troubles wrapping my head around the following situation.

I am trying to create a tree structure where I can provide custom names for connections between nodes.

So, I want to have Node and Relation models. Each

Node 
 has_many :relations

Each

Relation 
 has_many :nodes

Node can be either a parent or a child. So far, everything has been easy, and there are many examples that show how to make a has_many self-referencing table ... The problem is that I want to be able to give names to relationships so that I can do something like:

relation1 = node1.relations.create(:name => "relation_name", :child => node2)

and the result is something like:

relation1.name == "relation_name"
relation1.parent == node1
relation1.child == node2

All creations occur within the framework of the model, this activity is not really affected by the user, if it matters. Thank!

EDIT2: Here's how it works now:

class Node < ActiveRecord::Base
  belongs_to :sentence

  has_one :parent_relation, :foreign_key => "child_id", :class_name => "Relation"
  has_many :child_relations, :foreign_key => "parent_id", :class_name => "Relation"

  has_one :parent, :through => :parent_relation
  has_many :children,  :through => :child_relations, :source => :child

  has_many :relations, :foreign_key => "child_id"
  has_many :relations, :foreign_key => "parent_id"

class Relation < ActiveRecord::Base

  has_many :videos, :as => :videoable, :dependent => :destroy
  has_many :phrases, :through => :videos

  belongs_to :parent, :class_name => "Node"#, :inverse_of => :parent_relation
  belongs_to :child, :class_name => "Node"#, :inverse_of => :child_relation
+5
1

, , , .

. relation ', , "", .

, Node -

class Node < ActiveRecord::Base
   has_one  :parent_relation, :foreign_key => "child_id",
                              :class_name => "Relation"
   has_many :child_relations, :foreign_key => "parent_id", 
                              :class_name => "Relation"

   has_one  :parent, :through => :parent_relation
   has_many :children, :through => :child_relations, :source => :child
end

relation -

class Relation < ActiveRecord::Base
  belongs_to :parent, :class_name => "Node", :inverse_of => :parent_relation
  belongs_to :child, :class_name => "Node", :inverse_of => :child_relations
end

:inverse_of , Node parent children Node, magic :through. ( .)

, , . Lemme , - .

. relation - ActiveRecord, - NodeRelationship. , , .

+5

All Articles