Exclude draft articles from Solr index with Sunspot

本小妞迷上赌 提交于 2019-12-01 07:09:52

Be sure to index the published status.

class Article < ActiveRecord::Base
  searchable do
    text :title
    text :body
    boolean :is_published, :using => :published?
  end
end

Then add a filter to your query

Sunspot.search(Article) do |search|
  search.with(:is_published, true)
  # ...
end

If you want to make sure unpublished articles are never included in the search index, you can do it this way instead:

class Article < ActiveRecord::Base
  searchable :if => :published? do
     text :title
     text :body
  end
end

The model will then only be indexed when published.

My approach is less interesting if you also want admins to be able to search for articles, including unpublished ones, however.

Note: calling article.index! will add the instance to the index regardless of the :if => :method param.

A small look into the code base of sunspot_rails reveals a method called maybe_mark_for_auto_indexing which will be added to the models that include solr. You could override that method and set @marked_for_auto_indexing based on your criteria in the specific model. Its monkey patching but can help you solve the problem. The code for ur reference is in lib/sunspot/searchable.rb.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!