I want to highlight the words found in the text, for example, as shown here .
As far as I know, I should follow these steps:
1) In my model, I have to add a parameter :stored => trueto the field that I want to highlight:
searchable do
text :title, :stored => true
text :description
end
2) In my controller, I have to declare which field I want to highlight:
def search
@search = Article.search do
keywords params[:search] do
highlight :title
end
end
end
3) In the view, I'm not sure what to do, I tried this:
- @search.each_hit_with_result do |hit, result|
%p= link_to raw(hit_title(hit)), article_path(result)
This is what the method does hit_title:
def hit_title(hit)
if highlight = hit.highlight(:title)
highlight.format { |word| "<font color='green'>#{word}</font>" }
else
h(hit.result.title)
end
end
But it does not work as expected, it always highlights the first word of the title, even if the search word is at the end of it.
Is there an easier way to do this?