Skip to main content

What is a Smart Relationship?

Sometimes, you want to create a virtual relationship between two set of data that does not exist in your database. A concrete example could be creating a relationship between two collections available in two different databases. Creating a Smart Relationship allows you to customize with code how your collections are linked together.

Create a BelongsTo Smart Relationship

On the Live Demo example, we have an order which belongsTo a customer which belongsTo a delivery address. We’ve created here a BelongsTo Smart Relationship that acts like a shortcut between the order and the delivery address. A BelongsTo Smart Relationship is created like a Smart Field with the reference option to indicate on which collection the Smart Relationship points to. You will also need to code the logic of the search query.
class Forest::Order
  include ForestLiana::Collection

  collection :Order

  search_delivery_address = lambda do |query, search|

    query.joins(customer: :address).or(Order.joins(customer: :address).where("addresses.country ILIKE ?", "%#{search}%"))

  end

  belongs_to :delivery_address, reference: 'Address.id', search: search_delivery_address do
    object.customer.address
  end
end

Create a HasMany Smart Relationship

On the Live Demo example, we have a product hasMany orders and an order belongsTo customer. We’ve created a Smart Relationship that acts like a shortcut: product hasMany customers. A HasMany Smart Relationship is created like a Smart Field with the reference option to indicates on which collection the Smart Relationship points to.
class Forest::Product
  include ForestLiana::Collection

  collection :Product

  has_many :buyers, type: ['String'], reference: 'Customer.id'
end