Search code examples
ruby-on-railsactiverecordpolymorphismpolymorphic-associations

How to create an alias in a belongs_to declaration for a polymorphic relation in Ruby on Rails 5.2?


Several objects in my applicaton belong to a parent object with such relation:

  belongs_to :parent, :class_name => "Playground", :foreign_key => "playground_id"

I use the :parent declaration because this allows me to create a helper for building the breadcrums:

  def breadcrumbs(object)
    way_back = [object]
    while object.parent.class != Playground do # stop when comes to display the Playground
      path = object.parent
      way_back << path
      object = path
    end
    puts way_back.reverse
    way_back.reverse
  end

It gets more complicated for the BusinessObject class which is polymorphic. A Business Object belongs either to a Business Process, or to a Business Area. The relation is then defined as follow:

#  The parent relationship points to either Business Area or Business Process and relies on
#    area_process_type  :string
#    area_process_id    :integer

    belongs_to :area_process, polymorphic: true 

Thus, how can I define an alias to this belongs_to :area_process relation in order to use it as :parent elsewhere? Is there a syntax to declare a aliased belongs_to clause, or shall I create a method called "parent" for the Business Objects in order to solve this?

Addendum - the parent method could be this one:

### define the parent of current business object
  def parent
    parent_class = self.area_process_type.constantize
    parent_class.find(self.area_process_id)
  end

Thanks a lot.


Solution

  • You could use alias_attribute by adding the following to your BusinessObject model:

    alias_attribute :parent, :area_process