How to set up searchable multiple attributes for associated models for Sunspot search on Rails

StackOverflow https://stackoverflow.com/questions/21720373

  •  10-10-2022
  •  | 
  •  

Question

I have some models with relations as follows:

Order has many order_items (model OrderItem);

Order belongs to one vendor(model User) which has associated model Company.

And I want to make these full-text searchable based on Order:

1) OrderItem's attributes: name, description
2) vendor's company name

Then I set up the searchable attributes like this:

searchable do
... 
text :order_items do
  order_items.map { |item| item.name item.description }    # 1
end  

text :vendor do
  vendor.company.name  # 2
end

Both rows #1 and #2 will report as errors when do re-indexing.

So, please help how to write codes for both cases. Thanks.

Was it helpful?

Solution

You can write searchable methods on class and instance methods of the model. Do something like the following:

class Order

  searchable do
    text :order_items_search
    text :vendor_search
  end

  def order_items_search
    self.order_items.map{|item| item.name + ',' + item.description}.join(',')
  end

  def vendor_search
    self.vendor.company.name
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top