将计算列添加到ActiveRecord查询 [英] Adding a computed column to an ActiveRecord query
问题描述
我正在使用范围和某些条件来运行查询。像这样的东西:
I am running a query using a scope and some conditions. Something like this:
conditions[:offset] = (options[:page].to_i - 1) * PAGE_SIZE unless options[:page].blank?
conditions[:limit] = options[:limit] ||= PAGE_SIZE
scope = Promo.enabled.active
results = scope.all conditions
我想向查询中添加一个计算列(在我现在调用scope.all的时候)。像这样的东西:
I'd like to add a computed column to the query (at the point when I'm now calling scope.all). Something like this:
(ACOS(最小(1,COS(0.71106459055501)* COS(-1.2915436464758)* COS(RADIANS(addresses.lat)))* COS(RADIANS (addresses.lng))+
COS(0.71106459055501)* SIN(-1.2915436464758)* COS(RADIANS(addresses.lat))* SIN(RADIANS(addresses.lng))+
SIN(0.71106459055501) * SIN(RADIANS(addresses.lat)))* 3963.19)作为precision_distance
(ACOS(least(1,COS(0.71106459055501)*COS(-1.2915436464758)*COS(RADIANS(addresses.lat))*COS(RADIANS(addresses.lng))+ COS(0.71106459055501)*SIN(-1.2915436464758)*COS(RADIANS(addresses.lat))*SIN(RADIANS(addresses.lng))+ SIN(0.71106459055501)*SIN(RADIANS(addresses.lat))))*3963.19) as accurate_distance
有没有一种方法可以做到,而不仅仅是使用find_by_sql并重写整个现有查询?
Is there a way to do that without just using find_by_sql and rewriting the whole existing query?
谢谢!
推荐答案
当然,请使用:
conditions = Hash.new
conditions[:select] = "#{Promo.quoted_table_name}.*, (ACOS(...)) AS accurate_distance")
conditions[:offset] = (options[:page].to_i - 1) * PAGE_SIZE unless options[:page].blank?
conditions[:limit] = options[:limit] ||= PAGE_SIZE
scope = Promo.enabled.active
results = scope.all conditions
注意新的:select-告诉ActiveRecord您要返回的列。结果中返回的对象将具有#accurante_distance访问器。不幸的是,ActiveRecord太笨了,无法推断列的类型。您可以随时添加一个方法:
Note the new :select - that tells ActiveRecord what columns you want returned. The returned object in results will have a #accurante_distance accessor. Unfortunately, ActiveRecord is dumb and won't be able to infer the column's type. You can always add a method:
class Promo
def accurate_distance
raise "Missing attribute" unless has_attribute?(:accurate_distance)
read_attribute(:accurate_distance).to_f # or instantiate a BigDecimal
end
end
有关详细信息,请参见 #has_attribute 详细信息。
See #has_attribute for details.
这篇关于将计算列添加到ActiveRecord查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!