Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a search results page with pg_search multisearch that has links to the results?

I finally figured out how to implement pg_search's multisearch feature. But I'm having trouble making a usable search results page that displays links back to the various articles and faqs that contain the search terms. It's a pretty basic setup using Rails 3.2.3:

Models:

I have an Articles and a Faqs model, both with "Title" and "Content" attributes, and this code in both models:

include PgSearch
multisearchable :against => [:title, :content]

Search Form View Code:

The search form passes everything to a controller called "results."

<%= form_tag result_index_path, method: :get do %>
  <%= text_field_tag :query, params[:query] %>
  <%= submit_tag "GO", name: nil %>
<% end %>

Results Controller:

class ResultController < ApplicationController
  def index
     @pg_search_documents = PgSearch.multisearch(params[:query])
  end
end

I would like to make a search results page that displays the title of each result found, with a link back to that item. I figured out how to pull the 'class' attribute out @pg_search_documents. My thinking is to do something like this on the results page:

<ul>
<% @pg_search_documents.each do |pg_search_document| %>
  <li><%= link_to pg_search_document.searchable.title, "../#{pg_search_document.searchable.class}/#{pg_search_document.searchable.id}" %></li>
<% end %>
</ul>

An example link that this code yields is: http://localhost/Article/3. If I could figure out how to downcase and pluralize "pg_search_document.searchable.class", I'd be home free. I've tried writing various methods in the model and controller, and tried writing a helper. But this is where my Rails skills fail me.

Any suggestions? Anybody know of a more elegant way of accomplishing this? Any ideas / suggestions are very much appreciated.

like image 250
Gruntled Avatar asked May 27 '12 17:05

Gruntled


1 Answers

I did something similar and just used

<%= link_to pg_search_document.searchable.title, pg_search_document.searchable %>

to let Rails dynamically create the path to the associated record.

like image 79
Steve Grossi Avatar answered Nov 15 '22 13:11

Steve Grossi