使用SearchKick / ElasticSearch进行索引时如何加载相关模型?

时间:2016-08-22 21:45:57

标签: ruby-on-rails-3 elasticsearch searchkick

这是我的search_data方法:

def search_data
  {
    email: email,
    skills: interests.pluck(:name)
  }
end

我的User has_many :skills。当我运行User.where(conditions).reindex时,它会加载skills记录,例如

SELECT * FROM skills WHERE skills.user_id = 1
SELECT * FROM skills WHERE skills.user_id = 2
SELECT * FROM skills WHERE skills.user_id = 3
SELECT * FROM skills WHERE skills.user_id = 4
. . .

我想知道是否有可能让它像这样加载:

SELECT * FROM skills WHERE skills.user_id IN (1, 2, 3, 4, . . .)

1 个答案:

答案 0 :(得分:2)

您可以在建立索引时使用预先加载,因此要重新索引User模型,您需要编写User.includes(:skills).reindex

之类的内容

然后您也需要在map代替pluck

def search_data
  {
    email: email,
    skills: interests.map(&:name)
  }
end