I have a model Company. Companies consists of headquarters and branch_offices. They have exactly the same attributes (and won't change). Headquarters can have many branch_offices (optional association). Branch_offices belongs_to headquarter.
I would like to show the association in the API as follows (Note: some data removed as not relevant):
"data": { "id": "607424", "type": "companies", "attributes": { "commerce_register_data": { "uid": "US462745827168", "name": "Big Company Ltd", },
"branch_offices": [ { "uid": "US4852847292", "name": "Big Company Ltd, branch_office Chicago", "status": "ACTIVE", "legal_form": { "id": 9, "name": { "en": "Branch", }, "short_name": { "en": "Bran", } },
How can the relationship between headquarter and branch_offices shown? I came up with this thoughts after some research:
- Two models: Headquarter and Branch_office
- makes code much more complicated without additional benefit
- Query because the name follows the pattern: Some Company Name Ltd., branch_office City
- Slow performance and prone to errors
One additional model Branch with foreign keys of companies seems to complicated
Association within the same model, which I believe is possible according to my research (although I have never used it)
one additional column headquarter_id to branch_offices to Model Company
hope this will help
class Company < ApplicationRecord has_many :branch_offices, class_name: "Company", foreign_key: "headquarter_id" belongs_to :headquarter, class_name: "Company", optional: true end
eg:
branch_office = Company.find_by(name: "Big Company Ltd, branch_office Chicago") headquarter = branch_office.headquarter
headquarter = Company.find_by(name: "Big Company Ltd") branch_offices = headquarter.branch_offices