List of Projects OSRA - Support system Technical discussions Orphan osra_num: Reaching across 4 models

Orphan osra_num: Reaching across 4 models

Updated almost 6 years ago by Nikita Avvakumov

Generating osra_num for Orphan

Orphan's osra_num attribute is a numerical code for the client's internal use. Its first two digits must correspond to the Province code of the Partner who delivered the OrphanList containing the Orphan. Please refer to the highlighted paths in OSRA’s entity relationship diagram:

Current associations:

class Province < ActiveRecord::Base
  has_many :partners

class Partner < ActiveRecord::Base
  belongs_to :province
  has_many :orphan_lists
  has_many :orphans, through: :orphan_lists

class OrphanList < ActiveRecord::Base
  belongs_to :partner
  has_many :orphans

class Orphan < ActiveRecord::Base
  belongs_to :orphan_list
  has_one :partner, through: :orphan_list, autosave: false

Given the current associations, Province code can be reached from an Orphan object via self.partner.province.code. This is a clear violation of the Law of Demeter.

The situation can be remedied somewhat by using delegation:

class Partner < ActiveRecord::Base
  delegate :code, to: :province, prefix: true
class Orphan < ActiveRecord::Base
  delegate :province_code, to: :partner, prefix: true   province_code = self.partner_province_code

However, the chaining of delegations still goes against the spirit of the aforementioned law.

It must also be noted that the associations between an orphan and a partner, and between a partner and a province are effectively permanent. The application explicitly precludes changing of province for a persisted partner. Likewise, the association Partner-OrphanList-Orphan is set upon the initial data import and instantiation of objects, and persists throughout their lifetime. It is also extremely unlikely that the Province model’s code attribute will ever undergo any changes. Thus, there is very little actual brittleness in either of the two approaches shown above. If this is agreed upon, then delegations only add unnecessary complexity to the code base, and it is probably preferable to use the explicit method of retrieving the province code.


comments powered by Disqus