我正在尝试创建一个树结构,在那里我将能够为节点之间的连接提供自定义名称.
所以我想拥有Node和Relation模型.每
Node has_many :relations
每
Relation has_many :nodes
节点可以是父节点也可以是子节点.到目前为止,一切都很简单,并且有大量示例显示如何创建自引用的has_many表…问题是我希望能够为关系命名,以便我可以做类似的事情:
relation1 = node1.relations.create(:name => "relation_name",:child => node2)
并在结果得到类似的东西:
relation1.name == "relation_name"relation1.parent == node1relation1.child == node2
所有的创作都发生在模型中,如果重要的话,这个活动并没有真正暴露给用户.
谢谢!
EDIT2:
以下是它现在的工作原理:
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,:inverse_of => :child_relation解决方法 所以你所说的更像是 Joins Model而不是自我参考.
注意:我更改了您的关系协会“标签”,因为我的命名很难,因此您无需更改仅适合我的“标签”.
所以对于你的Node类,你可以做这样的事情
class Node < ActiveRecord::Base has_one :parent_relation,:class_name => "Relation" has_many :child_relations,:class_name => "Relation" has_one :parent,:through => :parent_relation has_many :children,:source => :childend
那么对于你的Relation类,你可以这样
class Relation < ActiveRecord::Base belongs_to :parent,:class_name => "Node",:inverse_of => :child_relationsend
::inverse_of选项应该让你构建让你根据你的Node实例中的父和子关联构建一个Node,这只是一个神奇的警告:通过关系. (此文档位于Joins Model部分的底部.)
我不完全理解你的关联结构,但我认为这应该正确建模. Lemme知道是否有任何问题.
附注:由于Relation是ActiveRecord模块中设置的常量,因此您可以考虑将其更改为NodeRelationship.我不认为它会干扰你的程序,但它确实给我的思考过程带来了一些麻烦.
总结以上是内存溢出为你收集整理的ruby-on-rails-3 – Rails自我引用has_many通过自定义连接表命名全部内容,希望文章能够帮你解决ruby-on-rails-3 – Rails自我引用has_many通过自定义连接表命名所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)