Ruby Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting started
    • How it works
    • Quick start
      • Ruby on Rails
    • Create your agent
    • Troubleshooting
    • Migrating legacy agents
      • Pre-requisites
      • Recommendations
      • Migration steps
      • Code transformations
        • API Charts
        • Live Queries
        • Smart Charts
        • Route overrides
        • Smart Actions
        • Smart Fields
        • Smart Relationships
        • Smart Segments
  • Data Sources
    • Getting Started
      • Collection selection
      • Naming conflicts
      • Query interface and Native Queries
        • Fields and projections
        • Filters
        • Aggregations
    • Provided data sources
      • ActiveRecord
        • Polymorphic relationships
      • Mongoid
    • Write your own
      • Translation strategy
        • Structure declaration
        • Capabilities declaration
        • Read implementation
        • Write implementation
        • Intra-data source Relationships
      • Contribute
  • Agent customization
    • Getting Started
    • Actions
      • Scope and context
      • Result builder
      • Static Forms
      • Widgets in Forms
      • Dynamic Forms
      • Form layout customization
      • Related data invalidation
    • Charts
      • Value
      • Objective
      • Percentage
      • Distribution
      • Leaderboard
      • Time-based
    • Fields
      • Add fields
      • Move, rename and remove fields
      • Override binary field mode
      • Override writing behavior
      • Override filtering behavior
      • Override sorting behavior
      • Validation
    • Hooks
      • Collection hook
      • Collection override
    • Pagination
    • Plugins
      • Write your own
    • Relationships
      • To a single record
      • To multiple records
      • Computed foreign keys
      • Under the hood
    • Search
    • Segments
  • Frontend customization
    • Smart Charts
      • Create a table chart
      • Create a bar chart
      • Create a cohort chart
      • Create a density map
    • Smart Views
      • Create a Map view
      • Create a Calendar view
      • Create a Shipping view
      • Create a Gallery view
      • Create a custom tinder-like validation view
      • Create a custom moderation view
  • Deploying to production
    • Environments
      • Deploy on AWS
      • Deploy on Heroku
      • Deploy on GCP
      • Deploy on Ubuntu
    • Development workflow
    • Using branches
    • Deploying your changes
    • Forest Admin CLI commands
      • init
      • login
      • branch
      • switch
      • set-origin
      • push
      • environments:create
      • environments:reset
      • deploy
  • Under the hood
    • .forestadmin-schema.json
    • Data Model
      • Typing
      • Relationships
    • Security & Privacy
Powered by GitBook
On this page
  • Displaying a link to the last message sent by a customer
  • Connecting collections without having a shared identifier

Was this helpful?

  1. Agent customization
  2. Relationships

Computed foreign keys

PreviousTo multiple recordsNextUnder the hood

Last updated 12 months ago

Was this helpful?

This is the official documentation of the agent_ruby Ruby agent.

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 as to why this is required),

  • create a relation using it.

Displaying a link to the last message sent by a customer

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 ForestAdminDatasourceCustomizer::Decorators::Computed
include ForestAdminDatasourceToolkit::Components::Query
include ForestAdminDatasourceToolkit::Components::Query::ConditionTree

@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: Nodes::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: Nodes::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.

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))
Under the hood