2015-04-26 50 views
1

這個問題之前已經被問了幾次並且回答了,但是沒有一個建議似乎適用於我的案例。Rails 4和太陽黑子:搜索幾個相關的模型

我有一個用戶模型和模型微柱

用戶有很多微觀柱,一個具有微柱一個用戶。

我想在使用太陽黑子的同時搜索用戶模型和微型模型。

我需要的是爲模型建立索引的正確語法。

我試過這樣:基於

sunspot solr how to search multiple models correctly? All examples online fail

class User < ActiveRecord::Base 
searchable do 
text (:full_name) 
text (:last_name) 
text (:first_name) 
text (:email) 
text (:job_title) 
text (:city) 
text (:country) 
text (:address) 
text (:tag_list) 
text (:content) { micropost.content } 
end 
end 

但這不起作用。我需要的只是搜索上面的micropost的內容屬性。所以如果一個人搜索一個用戶,他們會得到一個用戶,如果他們搜索了一個在micropost.content中出現的特定短語,他們就會得到這個短語的微博。

就我所見,文檔對此沒有幫助。

回答

1

用戶模式應該是這樣的:

class User < ActiveRecord::Base 
searchable do 
text (:full_name) 
text (:last_name) 
text (:first_name) 
text (:email) 
text (:job_title) 
text (:city) 
text (:country) 
text (:address) 
text (:tag_list) 
end 
end 

微柱模式應該是這樣的:

class Micropost < ActiveRecord::Base 
searchable do 
text (:content) 
end 
end 

然後,在你的search_controller.rb文件:

@search = Sunspot.search(User, Micropost) do |query| 
      query.fulltext params[:quick_search] 
      end 
@results = @search.results 

然後爲每個結果創建一個循環:

@results.each do |result| 
    if result.is_a?(User) 
    //do something with the result   
    end 
    if result.is_a?(Micropost) 
    //do something with the result   
    end 
end 
+0

不幸的是我得到這個錯誤「未定義的方法'MODEL_NAME」爲#<太陽黑子::搜索:: StandardSearch:0x007fa64e187648>」 – GhostRider

+0

如果您在DB有現有的數據使確保運行rake sunspot:solr:reindex'進行索引。對於新數據,索引將在鉤子中完成。 @GhostRider,在'indexing'之前重啓你的服務器。 – Emu