简体   繁体   English

Ruby on Rails:具有多个父级的层次模型

[英]ruby on rails: hierarchy model with multiple parents

I'm currently using ancestry gem to do a hierarchy list of my "posts", but I need to have the option to a child have multiple parents, and with ancestry I can't do that. 我当前正在使用祖先gem来创建我的“职位”的层次结构列表,但是我需要选择一个孩子有多个父母的选项,而对于祖先,我无法做到这一点。 You guys have any solution? 你们有什么解决办法吗? Adapting ancestry with other gem or using other gem instead. 与其他宝石适应血统或改为使用其他宝石。 Thanks 谢谢

Use HABATM association 使用HABATM关联

What you want to achieve is essentially has_and_belongs_to_many relationship. 您要实现的基本上是has_and_belongs_to_many关系。 You can create a relationship on yourself and that should do the trick. 您可以在自己身上建立一种关系,这应该可以解决问题。 If you need help on how to do this with HABTM association, here is a SO answer that shows how. 如果您需要有关如何与HABTM关联进行此操作的帮助, 这里有一个SO答案 ,说明了如何做。

class Post < ActiveRecord::Base
  has_and_belongs_to_many :children, 
              class_name: "Post", 
              join_table: :children, 
              foreign_key: :post_id, 
              association_foreign_key: :child_post_id
end

Alternatively, use a gem 或者,使用宝石

You can use acts-as-taggable-on gem to tag your posts. 您可以使用行为可标记的gem标记您的帖子。 It would be better if you create a model or enum that holds your tags, so that you don't mistype them while tagging. 如果创建一个保存标签的模型或枚举会更好,以免在添加标签时键入错误。

You can query your posts like this: 您可以这样查询您的帖子:

Post.tagged_with(["ruby", "rails"], :any => true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM