2016-11-04 64 views
0

我最近设置了searchkick,它对我已经建立索引的模型的属性非常有用。为什么我的searchkick has_many和HABTM关联不起作用?

但是,当涉及到关联时,它会失败。

这是我的模型协会& 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 

应该有至少5 profiles,但返回的结果为空。

我甚至试过格式化我的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协会和相应的声明。

什么可能导致这种情况,我该如何解决?

回答

0

因此,原来的search_data实际上是正确的,但我没有意识到我不得不运行rails searchkick:reindex:all命令,而不是仅仅做Profile.reindexrails console正运行。

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

相关问题