加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 将计算列添加到ActiveRecord查询

发布时间:2020-12-12 08:55:08 所属栏目:MsSql教程 来源:网络整理
导读:我正在使用范围和一些条件运行查询.像这样的东西: conditions[:offset] = (options[:page].to_i - 1) * PAGE_SIZE unless options[:page].blank? conditions[:limit] = options[:limit] ||= PAGE_SIZEscope = Promo.enabled.activeresults = scope.all condi
我正在使用范围和一些条件运行查询.像这样的东西:
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)as accurate_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

注意new: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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读