Rails facate with relationships

Hey,
Can anyone give me a tip on how to apply facate?
I am trying to get Bussines by ExternalServices with ExternalCategory that has delivery and booking

class Business < ApplicationRecord
  has_many :external_services, through: :external_service_links
end

class ExternalServiceLink < ApplicationRecord
  belongs_to :business
  belongs_to :external_service
end

class ExternalService < ApplicationRecord
  has_many :external_service_links, dependent: :destroy
  has_many :external_categories, as: :categorisable, inverse_of: :categorisable, dependent: :destroy
end

class ExternalCategory < ApplicationRecord
  CATEGORIES_TYPES = { external_service: %w[ delivery booking ...] }.freeze

  belongs_to :categorisable, polymorphic: true, touch: true # `touch` is needed for triggering indexing via `AlgoliaBusinessConfig`
end

and my algolia file

attributesForFaceting %i[ by_external_service ...]

attribute :by_external_service do
  %w[booking delivery].each do |category|
     external_services.select { |es| es.external_categories.pluck(:name).include?(category) }.map do |es|
       { category: es.external_categories.pluck(:name) }
     end
   end
end

def by_external_service_changed?
      false
end

it gives back all Businesses

solution:

attribute :by_external_service do
  external_services.select { |es| es.categories.include?('delivery') || es.categories.include?('booking') }.map do |es|
  { category: es.external_categories.pluck(:name)
  end
end
1 Like