-->

Using sunspot to search down model hierarchy

2019-08-03 04:52发布

问题:

Example:

I have the following:

class Person < ActiveRecord::Base
  has_many :educations
end

class Education < ActiveRecord::Base
  belongs_to :school
  belongs_to :degree
  belongs_to :major
end

class School < ActiveRecord::Base
  has_many :educations
  # has a :name
end

I want to be able to return all people who went to a specific school so in my PeopleController#index I have

@search = Person.search do
  keywords params[:query]
end

@people = @search.results

How do I create the searchable method on the Person model to reach down into school? Do I do something like this:

searchable do
  text :school_names do
    educations.map { |e| e.school.name }
  end
end

which I would eventually have to do with each attribute on education (degree etc) or can I make a searchable method on Education and somehow "call" that from Person.searchable?

Thanks

回答1:

It would be best if you keep the declaration of all the indexed fields for an specific model in the same place.

Also, you were doing a good job indexing :school_names, just do the same thing for the rest of the associations fields' that you want to index.