2016-11-04 61 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正運行。

一旦我運行了這個命令,我注意到它重新編制了包括所有關聯在內的所有內容,現在它就像一個魅力!

相關問題