我正在使用范围和一些条件运行查询。像这样的东西:
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 时)。像这样的东西:
(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) 作为accuracy_distance
有没有办法在不使用 find_by_sql 并重写整个现有查询的情况下做到这一点?
谢谢!
最佳答案
当然,使用这个:
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 很笨,无法推断列的类型。你总是可以添加一个方法:
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详情。
关于sql - 向 ActiveRecord 查询添加计算列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4687515/