回答

收藏

带有ActiveRecord和Rails 3的复杂JOIN

技术问答 技术问答 234 人阅读 | 0 人回复 | 2023-09-14

我有以下型号:  p( Z( ]4 j. s% Q' b) N, \
class User  :memberships
! ~* S: r' h; |' `, y" Uend4 V5 N8 E; m% b: T4 d
class Group  :memberships$ a; R5 g* D* t: b
end
" d$ D. a: Y2 m! }: z5 L; _class Membership 我必须找到属于user是成员的组的所有帖子。我已经用这种方法做到了:8 A9 Y! Q5 i( O: H  `# H2 i
@post = Post
$ d, u, z0 |( p. G$ w  .joins(:group => {:memberships => :user})6 ~% [1 w( ?9 K/ I1 K6 k' h
  .where(:memberships => {:user_id => current_user.id})  U" @( h# e( K. M
但它会产生无效的SQL:4 [$ b4 L' W4 M
SELECT "posts".* FROM "posts" " j" z$ y+ B7 M2 B0 e) B
INNER JOIN "groups" ON "groups"."id" = "posts"."group_id"
: s' [2 F" w9 y) X  x4 `. [INNER JOIN "memberships" ON "memberships"."group_id" = "groups"."id"
1 X9 F) W. K9 L3 MINNER JOIN "users" ON "users"."id" = "memberships"."user_id"
5 h: t1 N( z( a1 @WHERE "memberships"."user_id" = 1
3 H/ v  W5 q! B" W1 N% [3 D我想这样查询:9 D# z% `$ W; q9 y* ~% i* a
SELECT posts.* FROM posts % C" V. |. |! [
INNER JOIN memberships ON memberships.group_id = posts.group_id
$ y' C: S. t5 b% A0 T8 T2 OWHERE memberships.user_id = 1
* w  q# _& B2 x3 i% c. F( Y不使用原始SQL怎么办?4 N7 [3 {$ w9 @  c8 g
               
: H+ Z0 ?) i' J) ~3 |- _解决方案:- C8 S. Y' C: k3 g6 c* Z
               
! @3 T# t+ W; M
+ m. U! L5 }" W% p1 c- b' ~2 Q+ F" O! h
                像这样的事情应该为您工作,尽管它需要混入一些原始SQL
' ^2 |: i/ c0 s. QPost# T& k3 q' _4 U/ t; S
  .joins("INNER JOIN memberships ON memberships.group_id = posts.group_id")! U' M' d/ Z$ {" a3 _- y- n
  .where(:memberships => {:user_id => current_user.id})
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则