0

I am performing a sunspot (solr) search on a resource and filtering the results by my current users favorited resource. This works perfectly using the code below, however its requested that I sort the results and display when the user favorited that item (aka date created on the favorites model). I have no idea how to go about integrating that into my search while keeping the date specific to the user. Any ideas or solutions would be greatly appreciated.

class Resource < ActiveRecord::Base
  has_many :favorites
  has_many :favorite_users, through: :favorites

  searchable do
    text :title
    ...
    integer :favorite_user_ids, references: User, multiple: true
  end

  def self.full_search(params={}, current_user)
    search = Resource.search do
      keywords params[:term]
      with(:favorite_user_ids, current_user.id) if params[:filter] == 'favorite'
    end
    search
  end
end
Michael Lynch
  • 1,743
  • 15
  • 27

1 Answers1

0

Ahh, I see the problem-- you need to sort by the created_at date of a JOINED model, not one of the models you're indexing.

What if you moved the sunspot indexing to the Favorite model instead of the Resource? This would result in the Resource titles being indexed multiple times, but...

Something like this:

class Favorite
  belongs_to :resource
  belongs_to :user

  searchable do
    text :resource_title do
      resource.title
    end
    integer :user_id do
      user.id
    end
  end
end

Then you could have a searching method that does:

if params[:filter] == 'favorite'
  Favorite.search do
    keywords params[:term]
    with(:user_id, current_user.id)
    order_by(:created_at, :desc)
  end
end
carols10cents
  • 6,943
  • 7
  • 39
  • 56
  • However this will return the results of the favorites and not resources. – Michael Lynch Oct 18 '13 at 19:15
  • Right, but you can get the resource once you have a favorite. – carols10cents Oct 18 '13 at 20:18
  • with something like `@favorites.group_by(&:user)` – mathieugagne Oct 19 '13 at 18:29
  • Well, no, that will get you the favorites in subgroups as values in a hash with the users that go with those favorites as keys (I thought you only had 1 current_user?). To get a list of the favorites' Resources from a list of Favorites, you would want to do something like `@favorites.map(&:resource)` (since each favorite only has one resource). Or if you want to keep the favorites around, you should use `Favorite.search(:include => [:resource]) do` instead, like in [this question](http://stackoverflow.com/questions/8282344/sunspot-rails-include-associated-models-when-calling-results?rq=1). – carols10cents Oct 19 '13 at 18:51
  • Well, if I was searching on this only, then you're correct, this solutions seems to be a working one. However I'm performing a search on Resource using between 15-20 search parameters and around 10 different sorts, where by favorite date is just one. – Michael Lynch Oct 19 '13 at 20:56