Filter association in search results using rails sunspot

134 views Asked by At

I have this model

class Subject
  has_many: contents
  has_many: titles, :through => :contents

  searchable do
    text :titles, :default_boost => 5, :stored => true do
      my_titles = titles.map { |title| title.try(:name) }

      if my_titles.present?
        my_titles += titles.map do |title|
          title.path.map { |title| title.try(:name) }
        end
      end

      my_titles.flatten.uniq.join(" ")
    end
  end
end

class Title
  has_ancestry
end

When I'm searching for a subject it's working fine, but I need to add the feature to remove unnecessary Titles in my view. For example, when I search a Subject named "Human Biology", I get the result

Subject: Science 1
Titles: 
  - Environmental Science >> Human Biology # <-----this record need to stay
  - Chemistry 1 >> Chemistry 2 # <-----remove this
  - Physics 1 >> Physics 2 # <-----remove this

Subject: Science 2
Titles:
    Environmental Science >> Human Biology # <-----this record need to stay
    Chemistry 1 >> Chemistry 2 # <-----remove this

The Subjects appears in my search results, while I need to filter the titles based on what I searched for.

Here's my View:

<% @subjects.each_hit_with_result.each do |hit, subject| %>
  <% subject.titles.uniq.each do |title| %>
    <br/>
    <%=raw title.path.map {|e| link_to("#{e.name}", contents_url(:title => e.id) )}.join(' > ') %>
    <br/>
    <% end %>
  <% end %>
<% end %>

I tried to get the search params and use the select function, but I think this is not the right implementation.

1

There are 1 answers

0
Karol Wyliziński On

I guess this will help you to do a correct search.

Something like this

searchable do
  text :name
  join(:titles, target: Title, type: :text, join: { from: :subject_id, to: :id })
end