Polymorphic Associations / Forest Admin x Rails

Hi there,

On our Rails App, we’re using polymorphic associations (Active Record Associations — Ruby on Rails Guides).

The issue is that on Forest Admin, we don’t find a way to access to the associated record through a link. It’s just displayed as text :

On the screenshot above, category column is ‘product_type’, and product is ‘product_id’.

How can we do to create a link between this record and the product record. I’m looking into smart views/smart segments but I don’t find a way to do it.

Could you help ?

Thanks a lot !

Hi @yonitou,

We have an issue opened on the Forest Admin gem repository:

Unfortunately, it is not something we support natively so far.

Thanks for your answer !
Is there any work around ? I see that with smart relationship, I can create a belongs to association (which I succeed to make it work) but can I make it conditionnaly ?

Like

if object.product_type == wifi
  belongs_to :wifi, reference: 'Wifi.id' do
    object.product
  end
end

Hi @yonitou,

Unfortunately there is no ideal workaround to have a single relationship that links to different types of record.
What you could do is to create as many Smart “belongs to” associations as the types of records your polymorphic association can handle, but it would create a lot of new columns in your table view and only one would be filled in per record.

Hi !

This solution is fine for me.

The only issue is that, supposed that I have 2 types of different records, it’s filling both columns in the table. Am I able to fill only one column ?

Here’s my code snippet :

  collection :Subscription

  search_wifi = lambda do |query|

    Subscription.joins(product: :wifi).where("subscriptions.product_type = ?", "Wifi")

  end
  search_mobile = lambda do |query|

    Subscription.joins(product: :mobile).where("subscriptions.product_type = ?", "Mobile")

  end

  belongs_to :wifi, reference: 'Wifi.id', search: search_wifi do
    object.product
  end
  belongs_to :mobile, reference: 'Mobile.id',  search: search_mobile do
    object.product
  end

Ok, you just have to fine tune you belongs_to declaration from my point of view.

belongs_to :wifi, reference: 'Wifi.id', search: search_wifi do
  # if object.product is of type "Wifi"
  #   return object.product
  # else
  #  return nil
end
belongs_to :mobile, reference: 'Mobile.id',  search: search_mobile do
  # if object.product is of type "Mobile"
  #   return object.product
  # else
  #  return nil
end

Let me know if it helps

1 Like

Hi @arnaud!

Any chance polymorphic associations are now supported?

I don’t see update on it since a while!

Thanks :wink:

Hi @raphael-allard,

It is still natively not supported so far.
As the development team continues to grow, things could change in 2022.

1 Like

Hi @arnaud,

Thanks for sharing this info!

Please keep me in touch if there are some good news about it :slight_smile: