Search code examples
ruby-on-railsrubysunspot

Sunspot search for User


I use sunspot for my application. In my application, people can upload sounds in his account and i use sunspot for research the name of the sounds. But my search found all sounds and not only the user sounds.

In my controller i wrote that :

if params[:search].present?
    @search = Sunspot.search(Sound) do
      fulltext params[:search]


    end

    @sounds = @search.results
  else
    @sounds = Sound.order(:title).all
  end

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @sounds }
  end

But that list all of my Sounds not only the user's sound.

I hope i was clear in my request.

Thank's for help.


Solution

  • In sunspot we have :with argument there we can pass your own filter like

    Sounds.search do
      fulltext 'your text'
      with :user_id, 1
    end
    

    or

    if params[:search].present?
      @search = Sunspot.search(Sound) do
      fulltext params[:search]
    end
      @sounds = @search.results
    else
      @sounds = Sound.order(:title).all
    end
    respond_to do |format|
      format.html # index.html.erb
    format.json { render json: @sounds }
    end
    

    anyway @sounds having all the values so you could write one scope by_user and you can easily filter it.

    like @sounds.by_user(@user.id)

    more information please refer Railcast,Github,sunspot.github.io