views:

119

answers:

1

I am having many products with many categories which are associated with has_many using memberships.

I am trying to create a search box where any one can search products while also filter their search with a category dropdown (so only products with relevant categories can be retrieved).

The thinking_sphinx index is in Product model I don't get any errors but dropdown does not effect the search.



MODEL: 
    has_many :memberships,:dependent=> :destroy
    has_many :categories, :through => :memberships
    named_scope :published, :conditions => {:publish => 1}
    define_index do
        indexes product_name
        indexes product_description
        indexes publish
        indexes memberships.product_id
        indexes memberships.category_id
        indexes categories.category_name
      end
    end

CONTROLLER: 
     @products = Product.search params[:search],:conditions=>{@product.memberships.category_id =>params[:category_product] },:page=> params[:page] || 1,:per_page =>4


VIEW:
           form_tag search_path, :method =>:get do 
           text_field_tag :search, params[:search]
           form_tag categories_path, :method => :get do 
           select_tag"category", options_from_collection_for_select (Category.find (:all,   :group=>:id), :id, :category_name,params[:category_product]) 
           end 
           submit_tag "search", :name => nil 
           end 
+1  A: 

You need to use an attribute for filtering. In your define_index use a 'has' method, and in the search use a :with params. Something like :

define_index do
  …
  has categories(:id), :as => categories_id
  …
end

and the search would be :

Product.search params[:search], :with => { :categories_id => params[:category] }
tal
thnks i got it working,i am newbie it would be helpful if u just help me by clarify 2 things if possible1)in Product.search params[:search],:with=>{:categories_id => params[:category]}why it doesnt work if use params[:cat] i thought it was just accessing from my params[:cat] in view if i do so i get **searchd error (status: 1): invalid or truncated request2)if i try using name attribute instead of id it doesnot give any results eventhough it creates the query ex.model has categories(:category_name),:as =>categories_namecontroller{:categories_name=> params[:category]} thnx-a-lot-4-help
question 1, I do not understand (depends of your view, I guess).question 2, you cannot use a string in an attributes, only numbers and similar. It's better to use id anyway in this case. Or you have to first find the category by name before to fire the search
tal