2012-04-20 44 views
4

在我的Rails应用程序中,我使用太阳黑子来索引几个不同的模型。然后我有一个全球搜索表单,返回混合结果。这工作正常:Rails +太阳黑子:多模型搜索,但只有其中一个模型的某些领域?

Sunspot.search(Person, EmailAddress, PhoneNumber, PhysicalAddress) do 
    fulltext params[:q] 
    paginate :per_page => 10 
end 

我想添加一个额外的模型,说项目,这个搜索。项目模型有相当多的被索引:

class Project < ActiveRecord::Base 
    searchable do 
    string :category do 
     category.name.downcase if category = self.category 
    end 

    string :client do 
     client.name.downcase if client = self.client 
    end 

    string :status 

    text :tracking_number 
    text :description 

    integer :category_id, :references => Category 
    integer :client_id, :references => Client 
    integer :tag_ids, :multiple => true, :references => Tag 

    time :created_at, :trie => true 
    time :updated_at, :trie => true 
    time :received_at, :trie => true 
    time :completed_at, :trie => true 
    end 
end 

如何修改我原来Sunspot.search呼吁增加仅由tracking_number领域寻找项目记录和description场?

回答

0

我认为你必须将你的tracking_number定义为文本字段而不是字符串字段。仅在“文本字段”上进行全文搜索。

你有没有尝试这个办法:

text:tracking_number 

而且你的太阳黑子搜索样子:

Sunspot.search(Person, EmailAddress, PhoneNumber, PhysicalAddress, Project) do 
    fulltext params[:q] 
    paginate :per_page => 10 
end 

见你

+0

感谢您的回复。是的,我应该使用'text'方法。但是,我的意思是关注如何在进行多模式搜索时将搜索限制在给定模型的一个字段中。我会更新这个问题,以便更加精确。 – robertwbradford 2012-04-25 16:02:25

+0

我做了一个其他答案/解决方案 – Sebastien 2012-04-25 16:43:34

+0

但如何显示它在视图? – brabertaser19 2014-04-02 21:17:31

0

你尝试类似:

Sunspot.search(Post) do 
    keywords 'great pizza', :fields => [:title, :body] 
end 

你可以做一个r请求每个模型,然后将结果连接到一个列表中。我认为你无法在一次搜索中完成。

+0

再次感谢您的回复。我想这可能会起作用,但它似乎会破坏所有结果的分页和排序等。有没有解决的办法? – robertwbradford 2012-04-25 18:16:50

+0

使用will_paginate可以对concataned数组进行分页。我认为这不是问题。 – Sebastien 2012-04-26 08:34:07

+2

也打破基于分数的自动排序 – Kevin 2012-11-13 02:53:16

4
Sunspot.search(Person, EmailAddress, PhoneNumber, PhysicalAddress, Project) do 
    fulltext params[:q] do 
    fields(:tracking_number, :other_fields_outside_your_project_model) 
    end 

    paginate :per_page => 10 
end 

这将做TRACKING_NUMBER场和您指定的任何其他领域的全文搜索,特别是在你的人,EmailAddress的,******中国和PhysicalAddress模型。

+0

但如何显示它的视野? – brabertaser19 2014-04-02 21:16:04

+0

搜索将返回可能具有不同类型的匹配记录列表。调用respond_to后,您可以在记录中显示属性或方法的返回值?在该记录的属性/方法上。 – konyak 2014-04-03 04:26:05

+0

也许你可以给这个代码? – brabertaser19 2014-04-03 11:11:48