Search code examples
ruby-on-railssolrsunspot

Sunspot solr in rails need help to perform some query


I have a model User and Listing in my rails app. User has many listings and listing belongs to user. I also have a attribute name rating in user table. What I want is to search the keyword in Listing model and order it based on rating attribute of User model.

This is what I have in Listing model

searchable do  
    text :title, :default_boost => 3  
    text :description, :default_boost => 2  
    integer :category_id, :references => Category  
    integer :subcategory_id, :references => Subcategory  
    string :zipcode  
    time :created_at  
        double :user do  
        user.rating  
    end  
end

And this is how I am trying to search

@search = Sunspot.search(Listing) do  
    keywords params[:q]  do   
        fields :title  
    end  
    order_by THIS IS WHERE I NEED HELP    
    paginate :page => params[:page], :per_page => 20  
end  

Solution

  • You will need to add the keyword and rating attributes to the listing searachable method.

    class Listing < ActiveRecord::Base
      belongs_to :user
      searchable do
        text :keyword
        integer :rating { user.rating }
      end
    end
    

    Then in your search action in your controller

    Listing.search do
      fulltext params[:q]
      order_by :rating, :desc
    end
    

    See http://sunspot.github.com/ for more examples.

    Looking at your code, you need to change in your searchable method

    double :user do
      user.rating
    end
    

    to

    double :rating do
      user.rating
    end