Basic Setup for Multisearch in pg_search and Rails 3.2.3
Asked Answered
S

1

2

This is my very first question here, after many months of lurking and absorbing. So I hope I do this correctly.

I have been trying to get the multisearch functionality of pg_search working in my Rails 3.2.3 app after learning about the pg_search_scope functionality from this Railscast. I believe that the pg_search documentation assumes that the reader has a better working knowledge of Rails than I do. I just haven't been able to make the jump from the resources I've found to getting a working app using multisearch. Any help would be much appreciated. Here's my setup:

config/initializers/pg_search.rb

PgSearch.multisearch_options = {
  :using => {
    :tsearch => {
      :dictionary => "english"
    },
    :trigram => {}
  },
  :ignoring => :accents
}

Search Form in the View

<%= form_tag articles_path, method: :get do %>
    <%= text_field_tag :query, params[:query], :class => "search-box" %>
    <%= submit_tag "Search This Site", name: nil, :class => "btn btn-search" %>
<% end %>

article.rb

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

def self.search(query)
  if query.present?
    search(query)
  else
    scoped
  end
end

articles_controller.rb

def index
  @articles = PgSearch.multisearch(params[:query])

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @articles }
  end
end

I get no search results when searching for known terms. What am I doing wrong?

Sheetfed answered 14/5, 2012 at 3:22 Comment(0)
S
1

Looks like my error was using @articles variable in my controller instead of explicitly defining @pg_search_documents, which is what I was using in my view (which I completely forgot to post). For some reason I thought that using @articles = PgSearch.multisearch(params[:query]) in my controller would append the search results to `@pg_search_documents' via the pg_search magic sauce.

Sheetfed answered 14/5, 2012 at 12:28 Comment(1)
That's right. Instance variables set in the controller will get literally copied over to the view. You could have called your variable "@anything_at_all" and it would have to literally match in both places. I generally call my results "@results" to keep the typing simpler.Poilu

© 2022 - 2024 — McMap. All rights reserved.