问题
I have two models, School
model and Price
model. Every school has a price. Right now I get back the result I want, but I like to implement a sorting function that sorts the highest price for a school and the lowest.
School-controller:
class SchoolsController < ApplicationController
def index
@query = params[:search]
@search = School.search(:include => [:price] do
fulltext params[:search]
paginate :page => params[:page], :per_page => 7
end
@results = @search.results
end
end
School-model:
class School < ActiveRecord::Base
has_one :price
# sunspot search
searchable do
text :name, :locality
end
end
Index - view
<ul>
# Cheapest price
<li><span class="label label-ord">Show cheapest price <%= @query %></span></li>
# Highest price
<li><span class="label label-ord">Show highest price <%= @query %></span></li>
</ul>
<% for result in @results %>
<tr>
# School name, from the school-model
<td><h3><%= link_to result.name, result %></h3></td>
# School price, from the price-model
<td><h3><%= result.prices.min %> kr</h3></td>
</tr>
<% end %>
How can I sort the highest and lowest price; should I use facets or methods? How do I do that?
回答1:
I don't know sunspot really well, so i'm a bit guessing around here... Please consider what follows as a lead or advice, because i'm definitely not sure this will work.
The first step is to index the price for each school :
class School < ActiveRecord::Base
has_many :prices
searchable do
text :name, :locality
double :price do
# 'value' is just an example, use the relevant field on the price object
price.value if price.present?
end
end
end
Then reindex. Now you can order your searches:
@search = School.search( include: [:prices] ) do
fulltext params[:search]
paginate page: params[:page], per_page: 7
order_by :price, :asc # or use any param of your choice,
# returned by a select tag for example
end
Update
You can stick this logic in a class method.
class School < ActiveRecord::Base
def self.custom_search( text, page, order = :asc )
search( include: [:prices] ) do
fulltext text
paginate page: page, per_page: 7
order_by :price, order
end
end
end
then call with:
School.custom_search params[:search], params[:page]
# or :
School.custom_search params[:search], params[:page], :desc
来源:https://stackoverflow.com/questions/14541528/sorting-the-result-sunspot-rails