Can sunspot search inside array?

2019-03-29 13:49发布

问题:

I have the next model with a array field:

Class Invitation
 include Mongoid::Document
 include Mongoid::Timestamps::Created
 include Sunspot::Mongo

 field :recipients, :type => Array
 attr_accessible :recipients

 searchable do
  text :recipients do
  recipients.map { |recipient| recipient }
  end
 end

end

I have in my controller:

def recipients

 @invitation = Invitation.find(params[:id])
 @search = Invitation.search do |s|
 s.fulltext params[:search]
 s.with(:recipients, @invitation.recipients)
 end

@recipients = @search.results
  respond_to do |format|
   format.html
  end

end

This when I reindex not show error but:

This not works fine for me. I get the next error in log:

Sunspot::UnrecognizedFieldError (No field configured for Invitation with name 'recipients'):

I have tried too:

string :recipients do
  recipients.map { |recipient| recipient }
end

But I get the next error when I reindex:

recipients is not a multiple-value field, so it cannot index values []

Can I do fix this problem?

回答1:

The Invitation model has a has_many association with recipients. This means an invitation can have multiple recipients.

So, try this:

string :recipients, :multiple => true do
  recipients.map { |recipient| recipient }
end