Skip to content

Polymorphic associations

Andreas Dausenau edited this page Jun 30, 2023 · 2 revisions

Polymorphic associations

Since ez-on-rails needs the active record classes for automation purposes in some cases, polymorphic associations can not be handled like default associations, because the classes can not be found automatically.

But it is not impossible. Ez-on-rails also provides the necessary functionality to use polymorphic associations with some custom tweaks in the render_info.

First of all, you need to use the field type polymorphic_association like described in the render info documentation.

This article shows some special cases and tweaks to handle them.

Different label_nethod attributes

Suppose you have the models Payment, Organization and Customer. Payment has a target association that is polymorphic and can be an organization or customer. In our case the customer may does not have a name, but has a first_name and last_name. But the organization has only one name attribute. Hence we need a little trick here. We must define the label method on our own. The method must have the same name in both models.

class Customer < EzOnRails::ApplicationRecord
  ...
  def polymorphic_association_label
    "#{self.model_name.human}: #{first_name} #{last_name}"
  end
end

class Organization < EzOnRails::ApplicationRecord
  ...
  def polymorphic_association_label
    "#{self.model_name.human}: #{name}"
  end
end

Now we can use this method as label_method in the render_info.

def render_info_payment
  {
    target: {
      type: :polymorphic_association
      label: Payment.human_attribute_name(:target),
      label_method: :polymorphic_association_label,
      association_search_attributes: [:id],
      data: {
        organizations: Organization.all,
        customers: Customer.all
      }
    },
    ...
  }
end

Note that we also added the :association_search_attributes here. This is necessary because otherwise ez-on-rails would try to build a search field targetting the label_method that does not exist in the database here.

Clone this wiki locally