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