How can I order Sunspot search results for a query on multiple models?

I have two log models, ClientJournal

and InstitutionJournal

, and I am using Sunspot to run a query that grabs the records to display together on the log index page:

search = Sunspot.search ClientJournal, InstitutionJournal do
  paginate page: params[:page], per_page: 30
  order_by :created_at, :desc
end

      

This almost works, but it splits the results into two classes before ordering them, so it search.results

returns something like this:

created_at  class
09:30       ClientJournal
09:12       ClientJournal
08:57       ClientJournal
07:32       ClientJournal
09:45       InstitutionJournal
09:22       InstitutionJournal
09:07       InstitutionJournal

      

When I really want this:

created_at  class
09:45       InstitutionJournal
09:30       ClientJournal
09:22       InstitutionJournal
09:12       ClientJournal
09:07       InstitutionJournal
08:57       ClientJournal
07:32       ClientJournal

      

Is there a way to tell Sunspot to order the results together as if they were the same model?

+3


source to share


1 answer


you can do something like this to search multiple models and first get an individual array of models and then sort them like me: -



search = Sunspot.search ClientJournal,InstitutionJournal  do
           keywords(params[:search])
          #fulltext params[:search]
          order_by(:created_at, :desc)
          paginate :page => params[:page], :per_page => 10
         end 
##group them by class
 @results = search.results.group_by(&:class)
##get all clientjournals in created_at order
@clientjournals= @results[ClientJournal]
##OR do anything that you want with the array of cilentjournals
@clientjournals= @clientjournals.sort_by { |a| a.created_at }

      

0


source







All Articles