How to order search results by multiple fields?
Posted
by
JustinRoR
on Stack Overflow
See other posts from Stack Overflow
or by JustinRoR
Published on 2011-11-19T20:23:27Z
Indexed on
2011/11/20
1:51 UTC
Read the original article
Hit count: 217
I am using Sunspot and Will_paginate for search in my application and don't how to have my search results start out with certain ordering conditions.
The model I am searching is the UserPrice
model and want my :price
and :purchase_date
in descending order or lowest price to highest and present date to past:
class UserPrice < ActiveRecord::Base
attr_accessible :price, :product_name, :purchase_date
belongs_to :product
# Sunspot configuration
searchable do
text :product_name do
product.name
end
end
end
class SearchController < ApplicationController
def index
@search = UserPrice.search do
fulltext params[:search]
paginate(:per_page => 5, :page => params[:page])
end
@user_prices = @search.results
end
end
Even though I don't know how, I'm not sure if I would use Sunspot or Will_paginate to sort by order of price and purchase date. How would I achieve this though?
Thank you.
UPDATE
I try to use the order_by method but not sure how the model would look now.
class SearchController < ApplicationController
def index
@search = UserPrice.search do
fulltext params[:search]
paginate(:per_page => 5, :page => params[:page])
facet(:business_retail_store_id)
facet(:business_online_store_id)
order_by :price, :desc
order_by :purchase_date, :desc
end
@user_prices = @search.results
end
end
Not sure why having the following in my controller:
order_by :price, :desc
order_by :purchase_date, :desc
I get the error:
Sunspot::UnrecognizedFieldError in SearchController#index
No field configured for UserPrice with name 'price'
This doesn't make sense to me since I do have these fields inside of my UserPrice model and in my database. How do I fix this?
© Stack Overflow or respective owner