Rails 4按虚拟属性排序 [英] Rails 4 order by virtual attribute

查看:52
本文介绍了Rails 4按虚拟属性排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产品模型,该模型具有名称描述数据库中的列。

I have a Product model which has name and description columns in the database.

我也有一个 Product.search_results_for(query),其中 query 是类似于青苹果 的字符串。

I also have a Product.search_results_for(query), where query is a string like "Green Apple".

我需要返回效果最好的排序结果的 ActiveRecord :: Relation 。目前,我正在为每个产品设置 search_result_value search_result_value 不是数据库中的一列,我也不希望这样。

I need to return an ActiveRecord::Relation of the results ordered by which is the best hit. Currently, I'm setting a search_result_value to each product. search_result_value IS NOT a column in the database, and I don't want it to be.

所以从本质上讲,我有一个产品的 ActiveRecord :: Relation ,我需要按 search_result_value 进行排序,而无需将其更改为数组,这是一个未存储在数据库中的实例变量。我该怎么做?

So in essence, I have an ActiveRecord::Relation of Products that I need to order by search_result_value without changing it to an array, which is an instance variable that isn't stored in the database. How can I do this?

类似这样的东西:

Product.order(:search_result_value)


推荐答案

如果您不输入列中的值或在纯SQL中的 search_result_value 中表达逻辑,则必须将所有产品加载到内存中,然后使用 sort_by

If you do not put the value in a column or express the logic in search_result_value in pure SQL, then you’ll have to load all Products into memory and then sort them in Ruby using sort_by:

Product.all.to_a.sort_by(&:search_result_value)

这篇关于Rails 4按虚拟属性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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