为什么我的searchkick has_many和HABTM关联不起作用?

时间:2016-11-04 01:47:36

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

我最近设置了searchkick,它对我索引的模型上的属性非常有用。

然而,当谈到协会时,它会失败。

这是我的模特与协会& search_data方法:

class Profile < ActiveRecord::Base
  searchkick

  has_and_belongs_to_many :positions
  belongs_to :school

  def search_data
    {
      name: name,
      bib_color: bib_color,
      height: height,
      weight: weight,
      player_type: player_type,
      school_name: school.name,
      age: age,
      position_name: positions.map(&:name)
    }
  end
end

我确保运行Profile.reindex,但当我运行Center Back的查询时,position的名称,当我知道有> Profile.search("center back").to_a Profile Search (27.5ms) curl http://localhost:9200/profiles_development/_search?pretty -d '{"query":{"dis_max":{"queries":[{"match":{"_all":{"query":"center back","boost":10,"operator":"and","analyzer":"searchkick_search"}}},{"match":{"_all":{"query":"center back","boost":10,"operator":"and","analyzer":"searchkick_search2"}}},{"match":{"_all":{"query":"center back","boost":1,"operator":"and","analyzer":"searchkick_search","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}},{"match":{"_all":{"query":"center back","boost":1,"operator":"and","analyzer":"searchkick_search2","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"size":1000,"from":0,"timeout":"11s","_source":false}' => [] 时,它会返回一个空查询集结果

> p
=> #<Position:0x007fa881566310 id: 1, created_at: Sun, 04 Sep 2016 06:49:45 UTC +00:00, updated_at: Wed, 14 Sep 2016 06:17:02 UTC +00:00, name: "Center Back">
> p.profiles.count
   (4.1ms)  SELECT COUNT(*) FROM "profiles" INNER JOIN "positions_profiles" ON "profiles"."id" = "positions_profiles"."profile_id" WHERE "positions_profiles"."position_id" = $1  [["position_id", 1]]
=> 5

然而,结果是:

profiles

应该至少有5个search_data,但结果会返回为空。

我甚至尝试过格式化我的 def search_data attrs = attributes.dup relational = { school_name: school.name, grade_name: grades.map(&:subject), position_names: positions.map(&:name) } attrs.merge! relational end

has_many

如果我尝试定期https://api.soundcloud.com/tracks?client_id=xxxxxx 关联并相应地声明它,就会发生同样的事情。

可能导致此问题的原因以及如何解决?

1 个答案:

答案 0 :(得分:0)

事实证明search_data实际上是正确的,但我没有意识到我必须运行rails searchkick:reindex:all命令,而不是仅仅执行Profile.reindex正在运行的rails console

一旦我运行了这个命令,我注意到它重新编制了包括所有关联在内的所有内容,现在它就像一个魅力!