0

我有一个要求,我想根据传递给 sphinx 的 ID 顺序获得结果:

我用 ruby​​ 进行了排序和过滤,然后找到了 user_ids 的顺序

user_ids = [1, 3, 2]

现在,我想在此之上应用搜索:

User.search_for_ids("Test", {:with => {:page => params[:page], :per_page => 25, :sphinx_internal_id => user_ids}, :sql => {:order => "field(id,#{user_ids.join(',')})"}})

我看到当我们需要对 sql 进行排序时,我们可以在选项中传递 :sql => :order 。但这并没有按照预期的排序顺序给我结果。

User.where(:id =>  [1, 2, 3]).order("field(id,#{user_ids.join(',')})") 

给了我预期的正确结果

如果我在这里做错了什么,请纠正我。有没有办法保留关于 user_ids 的订单?任何帮助深表感谢。

4

2 回答 2

0

I don't believe there is a built-in mechanism for a predetermined sort order, but you can sort after the search results are returned. Obviously this won't work well if you're using any sort of pagination:

user_ids = [1,3,2]
results = User.search_for_ids #...
results.sort_by {|result| user_ids.index(result.id) }
于 2013-10-07T07:23:05.883 回答
0

我知道我的修复不是最佳的,但我最终做了类似下面的代码。考虑到“快速”狮身人面像的开销成本似乎并不太高。扎克的回答很好,但我还需要急切加载几个模型

product_ids = Product.seach_for_ids(term)
products = Product.includes(:manufacturer, :images, :items).where(:id => product_ids).order("field(ID,#{product_ids.join(",")})")

假设您使用的是 will_paginate gem,您应该能够在最后拍打分页,因为您将拥有一个 arel 对象

products = Product.includes(:manufacturer, :images, :items).where(:id => product_ids).order("field(ID,#{product_ids.join(",")})").paginate
于 2015-07-08T20:46:17.097 回答