【问题标题】:Rails 4 and Sunspot: searching across several related modelsRails 4 和 Sunspot:搜索多个相关模型
【发布时间】:2015-04-26 17:19:01
【问题描述】:

这个问题之前已经被问过好几次并得到了回答,但这些建议似乎都不适用于我的情况。

我有一个 User 模型和 Micropost 模型

一个用户有很多微博,一个微博有一个用户。

我正在尝试使用 Sunspot 同时搜索用户模型和微帖子模型。

我所需要的只是索引模型的正确语法。

我试过这个:

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

基于

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

但这不起作用。我只需要搜索上面微博的内容属性。因此,如果一个人搜索用户,他们就会得到一个用户,如果他们搜索出现在 micropost.content 中的特定短语,他们就会得到带有该短语的微博。

据我所知,文档对此没有帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 sunspot


    【解决方案1】:

    你的 USER 模型应该是这样的:

    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
    

    你的 MICROPOST 模型应该是这样的:

    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
    

    【讨论】:

    • 不幸的是,我收到此错误“#<:search::standardsearch:0x007fa64e187648> 的未定义方法 `model_name'”
    • 如果您在 DB 中有现有数据,请确保运行 rake sunspot:solr:reindex 进行索引。对于新数据,索引将在挂钩中完成。 @GhostRider,在indexing 重启你的服务器之前。
    猜你喜欢
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 2015-02-15
    • 1970-01-01
    • 2011-10-09
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多