title: Rails: Filtering with PG search not working
body: <p>I am currently building an online library in Ruby on Rails that has books which are in different subcategories and then categories. In other words;</p>
  
  <pre><code>Books belong to Subcategories
  Subcategories belong to Categories
  </code></pre>
  
  <p>I am using PG_search for search functionality, and here is my search method for searching books, <strong>which works fine</strong>:</p>
  
  <pre><code>pg_search_scope :search, 
                   against: [:name, :description, :author, :abstract],
                   associated_against: { category: [:name ], subcategory: [:name ] },
                   using: { tsearch: { prefix: true, dictionary: "english" } }
  </code></pre>
  
  <p>My index action of my controller looks like this:</p>
  
  <pre><code>def index
    if params[:query].present?
      @books = Book.search(params[:query])   
    else  
      @books= Book.all
    end
  end
  </code></pre>
  
  <p>But when I try to implement a <strong>filter by category</strong> in the index action of my books controller:</p>
  
  <pre><code>def index
    if params[:category].present? or params[:category][:id].present?
      @books = Category.find(params[:category][:id]).books.search(params[:query])   
    else  
      @books= Book.all
    end
  end
  </code></pre>
  
  <p>I encounter this error:</p>
  
  <blockquote>
    <p>undefined method `[]' for nil:NilClass</p>
  </blockquote>
  
  <p>Here is my view implementation</p>
  
  <pre><code>&lt;div class="advanceSearch"&gt;
    &lt;%= form_tag(books_path, method: :get) do %&gt;
        &lt;%= text_field_tag :query, params[:query], {placeholder: 'eg: Ruby', :class =&gt; 'searchForm'} %&gt;
        &lt;%= collection_select :category, :id, Category.all.order('name ASC'), :id, :name,{include_blank: 'Select Category'}, { :class =&gt; 'form-control'} %&gt;
      &lt;button type="submit"&gt;
        Search
        &lt;%= image_tag("searchIcon.svg", :alt =&gt; "search", :class =&gt; "") %&gt;
      &lt;/button&gt;
    &lt;% end %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I would appreciate any form of help that will enable me <strong>filter the books by category</strong> and <strong>subcategory if possible</strong>. Thanks.</p>