solr sunspot - 搜索belongs_to association

时间:2012-05-26 17:10:43

标签: ruby-on-rails ruby-on-rails-3 solr full-text-search sunspot

我有一个属于其他多个表的结构模型。

class Fabric < ActiveRecord::Base
  validates :name, presence: true
  belongs_to :design
  belongs_to :composition
  belongs_to :collection
  belongs_to :style
  belongs_to :origin
  belongs_to :texture
  belongs_to :supplier
  has_and_belongs_to_many :colours

  searchable do
    text :name, :boost => 5 
    text :description
    text :composition do
      composition.name
   end
    text :collection do
      collection.name
    end
   text :style do
     style.name
   end
   text :origin do
     origin.name
   end
   text :texture do
     texture.name
  end
   text :supplier do
      supplier.name
  end
  end
  end

我已经设置了所有反向关联(Has_many)等。 但是,我似乎无法通过全文搜索来查询所有这些关联表的名称字段。

非常感谢任何帮助。

 @search = Fabric.search do
    fulltext params[:search]
  end
  @fabrics = @search.results

罗斯

3 个答案:

答案 0 :(得分:10)

如果某些关联可能为零,请不要忘记测试,否则在重建索引时会出现错误

text :collection do 
  collection.name if collection
end

答案 1 :(得分:9)

您需要在全文中传递块以指定要搜索的字段。

@search = Fabric.search do
  fulltext params[:search] do
    fields(:collection, :style, :origin)
  end
  .....
end

以下是您在可搜索块中的索引方式。索尔在文件方面思考。它并不关心它是否是一种联想。

searchable do 
  text :collection do 
    collection.text 
  end
end

然后重新索引。

详情请查看https://github.com/sunspot/sunspot#full-text

https://github.com/sunspot/sunspot#setting-up-objects

答案 2 :(得分:3)

在模型更新后,您似乎没有重新编制索引数据。

运行此命令以重新索引:

bundle exec rake sunspot:solr:reindex
相关问题