【问题标题】:How to use scope in AR request with joins?如何在 AR 请求中使用范围与连接?
【发布时间】:2012-04-13 10:35:21
【问题描述】:

就我而言,我有一个模型产品 has_one Location

我使用地理编码器 gem 来搜索附近的位置。

请求 Location.near([0, 0], 100) 如下所示:

选择位置。*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((0 - locations.latitude) * PI() / 180 / 2), 2) + COS(0 * PI() / 180) * COS(locations.latitude * PI() / 180) * POWER(SIN((1 - locations.longitude) * PI() / 180 / 2), 2) )) 作为距离,CAST(DEGREES(ATAN2( RADIANS(经度 - 1), RADIANS(latitude - 0))) + 360 AS 十进制) % 360 AS 方位来自\"locations\" WHERE (6371.0 * 2 * ASIN(SQRT(POWER(SIN((0 - locations.latitude) * PI() / 180 / 2), 2) + COS(0 * PI() / 180) * COS(locations.latitude * PI() / 180) * POWER(SIN((1 - locations.longitude) * PI( ) / 180 / 2), 2) ))

我想做这样的事情:

Product.where(...).joins(:location).dosomething

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails activerecord arel


    【解决方案1】:

    Location#near 是一个命名范围?如果是这样,您可以使用 & 运算符将其与您的 Product 范围合并。我认为这应该可行:

    class Product
      scope :near, lambda { |coord, dist| joins(:location) & Location.near(coord, dist) }
    
      ...
    end
    

    那么你可以像这样使用它:

    Product.near([0, 0], 100)
    

    【讨论】:

    • 是的,它是一个作用域。我试了一下,得到了 3 个查询: 提案负载 (5442.1ms) SELECT "proposals".* FROM "proposals" INNER JOIN "locations" ON "locations"."locationable_id" = "proposals"."id" AND "locations "."locationable_type" = 'Proposal' 位置负载 (186.6ms) 选择位置。*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((0 - locations.latitude) ... 建议负载 (4920.5ms) SELECT "提案”。*来自“提案”
    • 什么是提案?你能显示Location#near的代码吗?
    • 合并范围似乎不起作用。它可能与near 范围内的select 有关。请参阅我的其他答案。
    【解决方案2】:

    另一种可能性,因为合并范围似乎不起作用:

    class Product
      scope :near, lambda { |coord, dist| where(:id => Location.near(coord, dist).all.map(&:locationable_id) }
    
      ...
    end
    

    和其他答案中的用法一样:

    Product.near([0, 0], 100)
    

    【讨论】:

    • 对不起。此解决方案不适用于生产
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2016-01-02
    • 1970-01-01
    • 2011-01-11
    相关资源
    最近更新 更多