简体   繁体   English

Find_by_sql作为Rails范围

[英]Find_by_sql as a Rails scope

r937 from Sitepoint was kind enough to help me figure out the query I need to return correct results from my database. 来自Sitepoint的r937非常友好,可以帮助我找出从数据库返回正确结果所需的查询。

What I need is to be able to use this query as a scope and to be able to chain other scopes onto this one. 我需要的是能够将此查询用作范围,并能够将其他范围链接到此范围。

The query is: 查询是:

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)

I tried making a scope like so: 我尝试制作这样的范围:

  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)')
  }

But when I tried chaining another one of my scopes onto it, it failed. 但当我尝试将另一个示波器链接到它上面时,它失败了。 Is there a way I can run this query like a normal scope? 有没有办法像普通范围一样运行此查询?

find_by_sql returns an Array . find_by_sql返回一个Array But you need an ActiveRecord::Relation to chain additional scopes. 但是你需要一个ActiveRecord::Relation来链接其他范围。

One way to rewrite your query using ActiveRecord methods that will return an ActiveRecord::Relation would be to rearrange it a little bit so that the nesting happens in the INNER JOIN portion. 使用将返回ActiveRecord::Relation ActiveRecord方法重写查询的一种方法是重新排列它,以便嵌套发生在INNER JOIN部分。

You may want to try something like: 你可能想尝试类似的东西:

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)")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM