gpt4 book ai didi

sql - Find_by_sql作为Rails范围

转载 作者:行者123 更新时间:2023-12-03 18:41:02 26 4
gpt4 key购买 nike

Sitepoint的r937足以帮助我确定需要从数据库返回正确结果的查询。

我需要的是能够将此查询用作作用域,并能够将其他作用域链接到该作用域。

查询是:

SELECT coasters.*
FROM (
SELECT order_ridden,
MAX(version) AS max_version
FROM coasters
GROUP BY order_ridden
) AS m
INNER JOIN coasters
ON coasters.order_ridden = m.order_ridden
AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)

我试图使像这样的范围:
  scope :uniques, lambda {
find_by_sql('SELECT coasters.*
FROM (
SELECT order_ridden,
MAX(version) AS max_version
FROM coasters
GROUP BY order_ridden
) AS m
INNER JOIN coasters
ON coasters.order_ridden = m.order_ridden
AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)')
}

但是,当我尝试将另一个示波器链接到它时,它失败了。有没有办法像正常作用域一样运行此查询?

最佳答案

find_by_sql返回一个Array。但是,您需要一个ActiveRecord::Relation来链接其他作用域。

一种使用ActiveRecord方法重写查询以返回ActiveRecord::Relation的方法是将其重新排列一点,以使嵌套发生在INNER JOIN部分中。

您可能想尝试类似的方法:

scope :uniques, lambda {
max_rows = select("order_ridden, MAX(version) AS max_version").group(:order_ridden)
joins("INNER JOIN (#{max_rows.to_sql}) AS m
ON coasters.order_ridden = m.order_ridden
AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)")
}

关于sql - Find_by_sql作为Rails范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25454696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com