【问题标题】:Searchkick indexing and then filtering on associations of associationsSearchkick 索引然后过滤关联的关联
【发布时间】:2021-02-09 05:48:41
【问题描述】:

我有一系列模型,我试图在 Rails 6 中使用 Searchkick 进行过滤,但由于关联具有关联,我遇到了一些麻烦。基本上,我有一个包含一些复杂关系的法庭文件数据库:

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

当然,courthousesmunicipalities search_data 对象并不完全正确,我似乎无法弄清楚它们。如果我按原样运行,我会收到如下错误:

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>)

有没有办法可以索引这些关联的关联,以便我可以将它们构建成可过滤的元素?一个case_event 可以有多个courthouses,而每个courthouse 只能有一个municipality——所以我有点不知道如何处理这个问题。

【问题讨论】:

    标签: ruby-on-rails elasticsearch searchkick


    【解决方案1】:

    答案很简单:

    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
    

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2015-09-11
      • 2013-10-10
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      相关资源
      最近更新 更多