简体   繁体   中英

Searchkick indexing and then filtering on associations of associations

I have a series of models that I'm trying to use for filtering purposes using Searchkick in Rails 6, but I'm running into some trouble due to associations having associations. Basically, I have a database on court filings with some complex relationships:

class Case < ApplicationRecord
  searchkick callbacks: :async,
    searchable: [:case_number, :case_event_short_titles, :case_event_party_names],
    filterable: [:case_type, :courthouses, :municipalities]

  scope :search_import, -> { includes(:case_events, :case_type) }

  has_many :case_events
  belongs_to :case_type

  def search_data
    {
      case_number: case_number,
      case_event_short_titles: case_events.map(&:short_title),
      case_event_party_names: case_events.map(&:party_name),
      case_type: case_type.name,
      courthouses: case_events.courthouse.map(&:name),
      municipalities: case_events.courthouse.municipality.map(&:name)
    }
  end
end

class CaseType < ApplicationRecord
  has_many :cases
end

class CaseEvent < ApplicationRecord
  belongs_to :case
  belongs_to :courthouse
end

class Courthouse < ApplicationRecord
  has_many :case_events
  belongs_to :municipality
end

class Municipality < ApplicationRecord
  has_many :courthouses
end

But of course, the courthouses and municipalities search_data objects aren't quite right, and I can't seem to figure them out. If I run this as-is, I get an error like:

Traceback (most recent call last):
        2: from (irb):1
        1: from app/models/case.rb:24:in `search_data'
NoMethodError (undefined method `courthouse' for #<CaseEvent::ActiveRecord_Associations_CollectionProxy:0x00005598dfc5f260>)

Is there a way I can index these associations-of-associations so that I can build them into filterable elements? A case_event can have multiple courthouses , and each courthouse can only have one municipality – so I'm a bit stumped as to how to handle this.

The answer turned out to be, quite simply:

def search_data
  {
    # Search
    case_number: case_number,
    title: short_title,
    case_event_title: case_events.map(&:short_title),
    case_event_party_name: case_events.map(&:party_name),

    # Where
    case_created_at: created_at,
    case_updated_at: updated_at,
    case_event_dates: case_events.map(&:date),
    case_event_created_at: case_events.map(&:created_at),
    case_event_updated_at: case_events.map(&:updated_at),
    courts: court.name,
    case_types: case_type.name,
    courthouses: case_events.map(&:courthouse).map(&:name),
    municipalities: case_events.map(&:courthouse).map(&:municipality).map(&:name)
  }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM