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.
include ForestAdminDatasourceCustomizer::Decorators::Computed
include ForestAdminDatasourceToolkit::Components::Query::ConditionTree
# Concatenate firstname, lastname and birthData to make a unique identifier
# and ensure that the new field is filterable
def create_filterable_identity_field(collection)
# Create foreign key on the collection from the database
collection.add_field(
'userIdentifier',
ComputedDefinition.new(
column_type: 'String',
dependencies: %w[firstName lastName birthDate],
values: proc { |users| users.map { |u| "#{u['firstName']}/#{u['lastName']}/#{u['birthDate']}" } }
)
)
# Implement 'In' filtering operator (required)
collection.replace_field_operator('userIdentifier', Operators::IN) do |values, _context|
{
aggregator: 'Or',
conditions: values.map do |value|
{
aggregator: 'And',
conditions: [
{ field: 'firstName', operator: Operators::EQUAL, value: value.split('/')[0] },
{ field: 'lastName', operator: Operators::EQUAL, value: value.split('/')[1] },
{ field: 'birthDate', operator: Operators::EQUAL, value: value.split('/')[2] }
]
}
end
}
end
end
# Create relationship between databaseUsers and crmUsers
def create_relationship(collection)
collection.add_one_to_one_relation(
'userFromCrm',
'crm_users',
{
origin_key: 'userIdentifier',
origin_key_target: 'userIdentifier'
}
)
end
# Create relationship between crmUsers and databaseUsers
def create_inverse_relationship(collection)
collection.add_many_to_one_relation(
'userFromDatabase',
'database_users',
{
foreign_key: 'userIdentifier',
foreign_key_target: 'userIdentifier'
}
)
end
@create_agent.customize_collection('database_users', &method(:create_filterable_identity_field))
@create_agent.customize_collection('crm_users', &method(:create_filterable_identity_field))
@create_agent.customize_collection('database_users', &method(:create_relationship))
@create_agent.customize_collection('crm_users', &method(:create_inverse_relationship))