【问题标题】:Sorting the result - sunspot rails排序结果 - 太阳黑子轨道
【发布时间】:2013-01-26 21:00:51
【问题描述】:

我有两个模型,School 模型和 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 %>

如何排序最高价和最低价;我应该使用方面还是方法?我该怎么做?

【问题讨论】:

  • @MrYoshiji - 有什么想法吗?或文档链接?
  • 您的问题模棱两可。您想获得所有结果的最高和最低价格,还是要按价格升序/降序对结果进行排序?此外,您希望它们成为所有搜索结果中的最高/最低价格,还是仅在分页结果中?
  • @m_x 对所有结果进行升序和降序排序。

标签: ruby-on-rails ruby ruby-on-rails-3 sunspot sunspot-rails


【解决方案1】:

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

第一步是索引每所学校的价格:

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

【讨论】:

  • 也许这可以工作,当我尝试重新索引时出现此错误:未定义的方法“任何?”对于 #<0x007fc78a2d5f60>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
相关资源
最近更新 更多