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

2

5

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.

Complaisance answered 27/5, 2012 at 17:8 Comment(0)
S
10

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.

Schmidt answered 19/6, 2012 at 19:27 Comment(0)
C
0

Well, it's amazing what walking away from the problem for a little while does. That, and more persistent Googling on basic Ruby. Here's the solution I came up with:

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

Still, this seems ugly to me. I'd still be very interested to see something more streamlined and intelligent.

Complaisance answered 28/5, 2012 at 1:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.