【发布时间】: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
当然,courthouses 和 municipalities 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