ruby-on-rails – 在Ruby on Rails Activerecord中将可计算列添加到具有eager_load的多表select子句

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Ruby on Rails Activerecord中将可计算列添加到具有eager_load的多表select子句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个查询与很多联接,我渴望加载一些当时的关联.我需要计算一些值作为其中一个模型的属性.

所以,我正在尝试这个代码

ServiceObject
  .joins([{service_days: :ou},:address])
  .eager_load(:address,:service_days)
  .where(ous: {id: OU.where(sector_code: 5)})
  .select('SDO_CONTAINS(ous.service_area_shape,SDO_GEOMETRY(2001,8307,sdo_point_type(addresses.lat,addresses.lng,NULL),NULL,NULL) ) AS in_zone')

其中sql函数调用select操作来自关联地址和表的数据.

我得到下一个sql(所以我的in_zone列获得计算并返回为所有eager_loaded模型的其他列之前的第一列):

SELECT SDO_CONTAINS(ous.service_area_shape,NULL) ) AS in_zone,"SERVICE_OBJECTS"."ID" AS t0_r0,"SERVICE_OBJECTS"."TYPE" AS t0_r1,<omitted for brevity> AS t2_r36 FROM "SERVICE_OBJECTS" INNER JOIN "SERVICE_DAYS" ON "SERVICE_DAYS"."SERVICE_OBJECT_ID" = "SERVICE_OBJECTS"."ID" INNER JOIN "OUS" ON "OUS"."ID" = "SERVICE_DAYS"."OU_ID" INNER JOIN "ADDRESSES" ON "ADDRESSES"."ID" = "SERVICE_OBJECTS"."ADDRESS_ID" WHERE "OUS"."ID" IN (SELECT "OUS"."ID" FROM "OUS" WHERE "OUS"."SECTOR_CODE" = :a1)  [["sector_code","5"]]

但是似乎in_zone无法从查询中使用的任一模型访问.

我需要计算出in_zone作为ServiceObject模型对象的属性,我该如何才能完成?

Ruby on Rails 4.2.6,Ruby 2.3.0,oracle_enhanced适配器1.6.7,Oracle 12.1

解决方法

那个猴子补丁帮助@Envek:
module ActiveRecord
  Base.send :attr_accessor,:_row_

  module Associations
    class JoinDependency
      JoinBase && class JoinPart
        def instantiate_with_row(row,*args)
          instantiate_without_row(row,*args).tap { |i| i._row_ = row }
        end; alias_method_chain :instantiate,:row
      end
    end
  end
end

那么可以做到:

ServiceObject
  .joins([{service_days: :ou},NULL) ) AS in_zone')
  .first
  ._row_['in_zone']

猜你在找的Ruby相关文章