0

I would like to use hidden field parameters(colour_id) to refine my search to fabrics associated with particular Colours.

Fabrics have many Colours, Suppliers and Categories

However I would like the paramers from hidden fields in my search form (colour_ids) to filter the fabrics, so that only fabrics associated with those colours are searched against.

From what I gather the best way of doing this would be to add scopes to my search, and pass the parameters of these hidden fields to the scope to narrow the search results to only fabrics that are associated with those colours.

My fabric model looks like this

class Fabric < ActiveRecord::Base
  has_many :fabric_categories
  has_many :categories, :through => :fabric_categories
  has_many :suppliers, :through => :fabric_suppliers
  has_many :fabric_suppliers
  has_many :colours, :through => :fabric_colours
  has_many :fabric_colours


  # solr search method
  searchable do
  text :name, :boost => 5
  text :description
  text :categories do
    categories.map(&:name)
  end
  text :suppliers, :boost => 2 do
   suppliers.map(&:name)
   end
  end

my controller

  class FabricsController < ApplicationController

  def index
    @search = Fabric.search do
    fulltext params[:search]

     #scoped assets
     @fabrics = @search.results

and my view

  <%= form_tag fabrics_path, :method => :get, :class => 'form-search'  do %>
    <%= text_field_tag :search, params[:search], :class => 'query', id: "auto_complete", :placeholder => '', :autocomplete => "off" %>
    <div id="colour_ids">
      <%= hidden_field_tag :colour_1 %>
    </div>
    <%= submit_tag "Search", :name => nil, :class => 'btn', :id => 'search_button' %>
  <% end %>
4

1 に答える 1

1

searchableブロックに含めることにより、category_idsをインデックスに追加する必要があります。

searchable do
  ...
  integer :colour_ids, :multiple => true do
    colours.map(&:id)
  end
end

これを行った後、インデックスを再作成する必要があります。

FabricsController#index次に、クエリに条件を次のように含める必要があります。

@search = Fabric.search do
  fulltext params[:search]
  with :colour_ids, params[:colour_1]
end
于 2012-06-18T18:18:53.960 に答える