【问题标题】:WITH Queries by ActiveRecord::QueryMethods And Return ActiveRecord_Relation rails通过 ActiveRecord::QueryMethods 查询并返回 ActiveRecord_Relation rails
【发布时间】:2017-07-31 08:31:51
【问题描述】:

我正在使用select in with 查询find_by_sql

scope :error_percentage, -> (user_obj) {
  find_by_sql("WITH products_boost_sum AS (SELECT *, (CASE WHEN (city_id =#{user_obj.user.city_id || -1}) THEN 1 ELSE 0 END) + (CASE WHEN (country_id =#{user_obj.country_id || -1}) THEN 1 ELSE 0 END) AS boost_sum FROM products) SELECT *, (CASE WHEN boost_sum = 2 THEN 2 ELSE 0 END) AS error_percentage FROM products_boost_sum")
}

这个范围被其他范围使用的问题。所以我需要返回 Active_Relation Object 而不是数组。 我检查了 ActiveRecord 的QueryMethods,但找不到with Query 的方法。

如何使用with Query 来返回 ActiveRelation 对象? 如果没有相应的 queryMethod,select 方法是否可用?

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord active-relation


    【解决方案1】:

    开箱即用的 Active Record 不支持 CTE 查询,但有一个 gem 增加了对 https://github.com/DavyJonesLocker/postgres_ext 的支持。

    然后你可以做类似的查询

    Score.with(my_games: Game.where(id: 1)).joins('JOIN my_games ON scores.game_id = my_games.id')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多