sunspot search assiocation using joins

136 views Asked by At

here's a list of model and their relation below:

class Section
  has_many :students, as: :resource

  searchable do 
    integer :id
    join(:first_name, prefix: "student", target: Student, type: :text, join: {from: :resource_id, to: :id})
    join(:last_name, prefix: "student", target: Student, type: :text, join: {from: :resource_id, to: :id})
   end
end

class Student
  belongs_to :resource, polymorphic: true, optional: false

  has_many :contact_number, as: :resource

  searchable do
    
    text :first_name
    text :last_name

    integer :id
    integer :resource_id


    string :first_name
    string :last_name

  end
end


class ContactNumber
  belongs_to :resource, polymorphic: true, optional: false
end

as you can see in my class model Section has many students. I can search student "first_name" and student "last_name" because of the help of joins. is there possible way to search student contact numbers. using of joins??? or what is the workaround to search the contact numbers in Section model?

1

There are 1 answers

0
imposterisasking On BEST ANSWER

in my ContactNumber model, i create an another joins

class ContactNumber
  searchable do
    string :ref_id do
      if resource_type == "Student"
        [resource.resource_type, resource.resource_id].join("_").downcase()
      end
   end
end

in my Student model

searchable do 
  string :ref_id do
  [resource_type, resource_id].join("_").downcase()
end

  join(:content, prefix: "contact_number", target: ContactNumber, type: :text, join: {from: :ref_id, to: :ref_id})
end

last in my Section class

class Section 
   searchable do
    string :ref_id do
  [self.class.name, id].join("_").downcase()
end
join(:content, prefix: "number", target: ContactPerson, type: :text, join: {from: :ref_id, to: :ref_id})
   end
end