Muhammad Rahmatullah
Muhammad Rahmatullah

Reputation: 326

Is there anyway to create children that have multiple parent from a model using tree Rails

currently, i've created an organization structure but it's some of the 'children' need a multiple parent. here is my current ancestry and i've implemented it to OrgChart

https://user-images.githubusercontent.com/16495060/34451193-918b25ae-ed51-11e7-9955-7694b0e6573f.png

My target is similar like this one :

enter image description here

i've using ancestry gem , but i'm kinda confused how to create multiple parent using that gem. i'll really appreciate any advice or suggestion

Upvotes: 2

Views: 370

Answers (1)

yeuem1vannam
yeuem1vannam

Reputation: 957

The ancestry gem using foreign key parent_id to store node A has what kind of relationship with node B, therefore, only 1 value can be stored in parent_id

That being said, you CANNOT make a node has multiple parents in a straight way.

However, back to your data structure that you want to implement, the definition seems not clear. If I understand correctly from your diagram, it is:

  • There are some groups of people, suppose group A and group B
  • Group A has multiple users: WAKIL, KOORDINATOR, BAGIAN
  • Group B has multiple users: PEM, INTELE, PIDANA, ...
  • Group A has a relationship parent-children with group B

In this case, your actual tree should only presenting about relationship between groups

Group X
↓
Group Y
↓
Group A
↓
Group B

and the definition of users in group B has multiple parents from group A will become

Group A has_many: users
Group B has_many: users

So from now on, your models will become

# app/models/user.rb
class User < < ActiveRecord::Base
  belongs_to :group
end

# app/models/group.rb
class Group < ActiveRecord::Base
  has_ancestry
  has_many :users
end

Hope it helps.

Upvotes: 2

Related Questions