Search code examples
ruby-on-railsruby-on-rails-3solrsunspotsunspot-rails

Using sunspot_solr search array of values


Hi, I built a Ruby on Rails application with Sunspot Solr for searching.

@search = Answer.search do
  with(:question_id, @question_ids) 
  paginate :page => 1, :per_page => Answer.count
end
return question_id

Here i want to search this Answer model using array of question_ids (ex: [1,2,3,4,5]).

How to do that? Kindly help me.


Solution

  • if your question and answer has association like

    class Question < ActiveRecord::Base
       has_many :answers
    end
    
    class Answer < ActiveRecord::Base
      belongs_to :question
    end
    

    then you can add searchable to your questions model like this

    class Question < ActiveRecord::Base
      searchable do
        text :title, :body
        text :answers do
          answers.map { |answer| answer.body }
        end
        integer :questions_ids, :multiple => true
      end
        // your another methods
    end
    

    And in your index action

    @search = Answer.search do
      with(:questions_ids, @question_ids) 
      paginate :page => 1, :per_page => Answer.count
    end
    return question_id
    

    I think it will help you.