how to use postgresql condition with solr sunspot rails

265 Views Asked by At

I have a list of posts with status which means

status 1 - active
status 0 - removed
status 2 - pending

My solr seearch in index everything so if I search It is showing all the posts irrespective of the status code. I need only posts with status 1

I tried something like this

@search = Post.where(status: 1).search do
      fulltext params[:search] do
        minimum_match 1
      end
      paginate page: params[:page], per_page: 15
    end
    @posts = @search.results
    respond_to do |format|
      format.json { render nothing: true }
      format.html
    end

How can I do this. Can anyone help.

1

There are 1 best solutions below

1
On

Instead of @search.results, you can use @search.result_ids in an ActiveRecord where clause.

@posts = Post.where(:id => @search.result_ids).where(status: 1)

This actually isn't a great option, because if your search is including results that don't have the status you want, then the pagination isn't going to match up nicely with your database.

Better to index the status field in your model's searchable block, and instruct Solr to filter on that column in your search.

class Post
  searchable do
    # other fields...
    integer :status
  end
end

@search = Post.search do
  # other search options
  with :status, 1
end

@posts = @search.results