Computed foreign keys

You may want to create a relationship between 2 Collections, but you don't have a foreign key that is ready to use to connect them.

This is done with the following steps:

  • create a new Field containing a foreign key,

  • make the Field filterable for the In operator (see Under the hood as to why this is required),

  • create a relation using it.

We have 2 Collections: Customers and Messages, linked together by a one-to-many relationship.

We want to create a ManyToOne relationship with the last message sent by a given customer.

include ForestAdmin::Types

@create_agent.customize_collection('customer') do |collection|
  # Create foreign key
  collection.add_field(
    'lastMessageId',
    ComputedDefinition.new(
      column_type: 'Number',
      dependencies: ['id'],
      values: proc { |customers, context|
        customer_ids = customers.map { |r| r['id'] }

        # We're using Forest Admin's Query Interface
        filter = Filter.new(
          condition_tree: ConditionTreeLeaf.new('customer_id', Operators::IN, customer_ids)
        )
        aggregation = Aggregation.new(operation: 'Max', field: 'id', groups: [{ field: 'customer_id' }])
        rows = context.datasource.get_collection('message').aggregate(filter, aggregation)

        customers.map do |customer|
          row = rows.find { |r| r['group']['customer_id'] == customer['id'] }
          row ? row['value'] : nil
        end
      }
    )
  )
  .replace_field_operator('lastMessageId', Operators::IN) do |last_message_ids, context|
    filter = Filter.new(
      condition_tree: ConditionTreeLeaf.new('id', Operators::IN, last_message_ids)
    )
    records = context.datasource.get_collection('message').list(filter, Projection.new(['customer_id']))

    { field: 'id', operator: 'In', value: records.map { |r| r['customer_id'] } }
  end
  .add_many_to_one_relation('lastMessage', 'message', { foreign_key: 'lastMessageId' })
end

Connecting collections without having a shared identifier

You have 2 Collections and both contain users: one comes from your database, and the other one is connected to the CRM that your company uses.

There is no common id between them that can be used to tell Forest Admin how to link them together, however, both Collections have firstName, lastName, and birthDate fields, which taken together, are unique enough.

Last updated

Was this helpful?