|
Sitepoint的r937足以帮助我确定需要从数据库返回正确结果的查询。2 B& Q7 g1 A8 v9 g8 D
我需要的是能够将此查询用作作用域,并能够将其他作用域链接到该作用域。
6 p8 N/ a" c- t% i4 E$ f3 N/ b2 K查询是:
`) B! l% H qSELECT coasters.*& U$ G Q3 Q3 U! i- H; \
FROM (. e# N/ j/ o5 a5 @- T
SELECT order_ridden,2 R( X9 C* Y0 _6 u- L$ ?
MAX(version) AS max_version9 L; w, H p4 d) h
FROM coasters
N7 J% H5 a1 P, o6 E, }- a GROUP BY order_ridden' {/ P3 }) d7 k# e
) AS m6 |, Y0 N; T( B2 y1 h, B
INNER JOIN coasters+ I& L5 X+ i, [2 Z8 Z
ON coasters.order_ridden = m.order_ridden5 n) l0 O' k+ P/ y0 K# v# }" H3 e
AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)
. \+ _ }& K7 Q h我试图使像这样的范围:( e- j2 a$ N' i8 H" y2 L# m
scope :uniques, lambda {
( I0 P: p) w* c2 ^2 K find_by_sql('SELECT coasters.*
4 Z* w; u) n$ h- z; K" \. @# L4 A; y FROM (
+ P; V2 B4 l8 g. ~" [5 q1 h4 i SELECT order_ridden,
2 J3 l3 n! v. `3 X' @/ R MAX(version) AS max_version
+ r8 f, `; W# J' } FROM coasters! V8 J4 y9 F9 H; m: Y
GROUP BY order_ridden
+ r' w- m" m2 K/ a: c7 T& ? ) AS m
0 j0 R- {: M( `3 l" Y INNER JOIN coasters8 C$ s: U/ @9 t2 E4 ~
ON coasters.order_ridden = m.order_ridden2 h6 Z; \ ~% l8 f0 e
AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)')
+ n7 X4 ?; q9 T9 W2 Z+ _! u }
) W5 x3 Q$ |& r; Z- J) u8 L2 E但是,当我尝试将另一个示波器链接到它时,它失败了。有没有办法像正常作用域一样运行此查询?' Z3 Q# z. M' U# U: R
j( G8 p( F* h7 Q6 h& ]
解决方案:* X* k5 m+ t! T( i6 w
* `, ]. ]6 w1 R0 ^! y
& ?9 @ }7 a% L2 k% O* P( G7 `2 k! f3 Y* b) t% U6 D# }- h
find_by_sql返回Array。但是您需要ActiveRecord::Relation链接其他作用域。
) P1 h' f5 V( r' B0 x# _' F; p使用将返回的ActiveRecord方法重写查询的一种方法是将ActiveRecord::Relation其重新排列一点,以使嵌套发生在该INNER8 d( s. n; d x
JOIN部分中。2 X7 A9 m2 b8 }3 z' q8 k
您可能想尝试类似的方法:0 E! T9 g- m* e1 A
scope :uniques, lambda {
/ E1 j5 A$ r' L; x7 h% ]+ p max_rows = select("order_ridden, MAX(version) AS max_version").group(rder_ridden). X1 S/ j) _, E! b$ u
joins("INNER JOIN (#{max_rows.to_sql}) AS m7 O, b, r6 {! o+ N& v' F" l
ON coasters.order_ridden = m.order_ridden
0 H L+ G4 ^$ ]7 G5 v' t, Z* V AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)")- |# K" x: a; [+ h; W
} |
|