Search code examples
ruby-on-railselasticsearchsearchkick

Searchkick : GrandParent has_many Parent - Parent has_many Child


I'm working on search in a Ruby on Rails application using searchkick gem.

I have, say, three models GrandParent , Parent , and Child where:

class Parent < ApplicationRecord
    has_many :childs

and

class GrandParent < ApplicationRecord
    has_many :parents

Say, Parent has a value name. And Child has a value content

When I try to find records in GrandParent which have parents with name that matches the search query I can use the following:

searchkick

def search_data
    {
        parents: parents.map(&:name).join(' '),
    }
end

But, how can I perform search to find records in GrandParent which have parents having childs with content value matching the search query?

In other words, if the query matches the content of a Child , It's GrandParent should be returned in the search result.


Solution

  • I had it done by adding the following to GrandParent model:

    searchkick
    
    def search_data
        {
            parents: parents.map(&:name).join(' '),
            childs: get_childs_contents.join(' ')
        }
    end
    
    def get_childs_contents
        a = []
        parents.each do |p|
            p.childs.each do |c|
                a << c.content
            end
        end
        return a
    end