【发布时间】:2017-11-30 00:45:42
【问题描述】:
我正在使用 searchkick 和 rails4。
我有一个活动记录 People,具有 a、b、c 属性。如何仅当 b 等于“type1”时才进行索引,否则不进行索引?
目前我知道的是
def search_data
{
a:a,
b:b,
c:c,
}
end
【问题讨论】:
标签: ruby-on-rails-4 searchkick
我正在使用 searchkick 和 rails4。
我有一个活动记录 People,具有 a、b、c 属性。如何仅当 b 等于“type1”时才进行索引,否则不进行索引?
目前我知道的是
def search_data
{
a:a,
b:b,
c:c,
}
end
【问题讨论】:
标签: ruby-on-rails-4 searchkick
有点晚了,但今天早些时候有一位队友提出了这个问题,我认为这个话题值得更详细的回答。
据我所知,您有两个选项来控制哪些记录被 searchkick 索引:
在类级别,您可以通过定义 ActiveRecord 范围 search_import 来限制记录 searchkick 索引。本质上,此范围用于一次索引多条记录时,例如运行 searchkick:reindex 任务时。
在实例级别,您可以定义一个should_index? 方法,该方法会在索引之前对每条记录调用,它决定是否应从索引中添加或删除记录。
因此,如果您只想索引 b 等于 'type1' 的记录,您可以执行以下操作:
class People < ApplicationRecord
scope :search_import, -> { where(b: 'type1') }
def should_index?
b == 'type1'
end
end
请注意,从should_import? 返回false 将删除索引中的记录,因为您可以阅读here。
【讨论】:
根据docs:
默认情况下,所有记录都被索引。要控制对哪些记录进行索引,请将
should_index?方法与search_import范围结合使用。
这应该适用于您的情况:
class People < ApplicationRecord
searchkick # you probably already have this
scope :search_import, -> { where(b: "type1") }
def should_index?
self.search_import # only index records per your `search_import` scope above
end
def search_data # looks like you already have this, too
{
a:a,
b:b,
c:c,
}
end
end
【讨论】:
b。 def should_index? 仅索引在 should_index? 块内返回的记录。而且,self.search_import? 将调用search_import 范围,它只会返回b == "type1" 所在的记录,这意味着这些记录将被索引。
如果您想在should_index? 中使用:search_import 范围,如上面BigRon 的回答所示,您需要通过self.class.search_import 访问范围。
class People < ApplicationRecord
searchkick # you probably already have this
scope :search_import, -> { where(b: "type1") }
def should_index?
self.class.search_import # only index records per your `search_import` scope above
end
def search_data # looks like you already have this, too
{
a:a,
b:b,
c:c,
}
end
end
【讨论】: