1

Schoolモデルとモデルの2つのモデルがありPriceます。すべての学校には価格があります。今は欲しい結果が返ってきましたが、学校の最高価格と最低価格を並べ替える並べ替え関数を実装したいと思います。

学校の管理者:

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

どうすれば最高価格と最低価格を並べ替えることができますか。ファセットまたはメソッドを使用する必要がありますか?それ、どうやったら出来るの?

4

1 に答える 1

2

私は太陽黒点をよく知らないので、この辺りはちょっと推測しています...これがうまくいくかどうかは絶対にわからないので、次のことをリードまたはアドバイスとして考えてください.

最初のステップは、各学校の価格をインデックス化することです。

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

次に、再インデックスします。これで、検索を並べ替えることができます:

 @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

アップデート

このロジックをクラス メソッドに貼り付けることができます。

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
于 2013-01-26T22:32:37.333 に答える