0

Is it possible, in Rails (4 or 5) to set this kind of relationship between models:

  • Model A has many Models B
  • Model B has many Models B

I don't know if there is a good approach to these relationships, or if it's better to change the model data.

R. Sierra
  • 1,076
  • 6
  • 19
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
  • Possible duplicate of [Many-to-many relationship with the same model in rails?](http://stackoverflow.com/questions/2168442/many-to-many-relationship-with-the-same-model-in-rails) – Gerry Mar 14 '17 at 14:10
  • @Gerry the problem is that it's not only the many-to-many with the same model. The same model (B) can belong to another one, at the same time. – Christian Benseler Mar 14 '17 at 14:14

1 Answers1

1

The first relationship is a standard one-to-many (or even many-to-many) relationship, and the second one "Model B has many Models B" fits Self Joins:

In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:

class Employee < ApplicationRecord
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id"

  belongs_to :manager, class_name: "Employee"
end
marcanuy
  • 23,118
  • 9
  • 64
  • 113