使用ActiveRecord的查询:: QueryMethods并返回ActiveRecord_Relation rails

问题描述 投票:1回答:1

我正在使用select in withfind_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对象而不是数组。我检查了ActiveRecord的QueryMethods,但我找不到with Query的方法。

如何使用with Query返回ActiveRelation对象?如果没有queryMethod,select方法可以使用它吗?

ruby-on-rails postgresql activerecord active-relation
1个回答
0
投票

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')
© www.soinside.com 2019 - 2024. All rights reserved.