排序结果 - 太阳黑子轨道 [英] Sorting the result - sunspot rails

查看:44
本文介绍了排序结果 - 太阳黑子轨道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,School 模型和 Price 模型.每个学校都有价格.现在我得到了我想要的结果,但我喜欢实现一个排序功能,对学校的最高价格和最低价格进行排序.

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.

校方:

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

学校模式:

class School < ActiveRecord::Base
 has_one :price
 # sunspot search
  searchable do
   text :name, :locality
  end
end

索引 - 查看

<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?

推荐答案

我不太了解太阳黑子,所以我在这里有点猜测...请考虑以下内容作为线索或建议,因为我我绝对不确定这会起作用.

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

更新

您可以将此逻辑粘贴到类方法中.

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

然后调用:

School.custom_search params[:search], params[:page]
# or :
School.custom_search params[:search], params[:page], :desc

这篇关于排序结果 - 太阳黑子轨道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆