I need the ability to search for a user's specific items through has_many associations.
I originally had searchkick
on my Items model, and now have it on my User model. I also had asked a question a few weeks ago for this same question, however I received no responses and have modified the code quite a bit since then.
class User < ApplicationRecord
searchkick
has_many :items, -> (user) { unscope(:where).where("(consumer_type = ? and consumer_id = ?))", 'User', user.id) }, fully_load: false, dependent: :destroy
def search_data
attributes.merge(
items: library_items.as_json,
)
end
end
In my controller, I need the ability to run a query such as: @results = current_user.items.search('Query')
, so that I return items that only that user has access to.
Currently, when I run something like this in rails console: user = User.first user.search 'Email' I get `undefined method 'search' for #
How do I go about correctly setting something like this up? Should I actually put searchkick
on the Item model? If so, how would I then go about searching
My approach to this would be to index the Item
model using Searchkick, as it's easier to achieve your desired result that way, especially if you only want information about the items returned in your results (and not necessarily user data as well).
You could then search the Item
model using something like:
@results = Item.search(
'Query',
where: {consumer_type: 'User', consumer_id: current_user.id},
load: false
)