Reputation: 1743
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
Upvotes: 0
Views: 509
Reputation: 7014
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
Upvotes: 0