带有ActiveRecord和Rails 3的复杂JOIN [英] Complex JOIN with ActiveRecord and Rails 3
本文介绍了带有ActiveRecord和Rails 3的复杂JOIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模型:
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, :through => :memberships
end
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
class Post < ActiveRecord::Base
belongs_to :group
end
我必须查找所有属于user是成员的组的帖子。我已经用这种方法做到了:
I have to find all posts that belong to groups where user is a member. I have made it with this method:
@post = Post
.joins(:group => {:memberships => :user})
.where(:memberships => {:user_id => current_user.id})
但它会产生无效的SQL:
but it produces unefficient SQL:
SELECT "posts".* FROM "posts"
INNER JOIN "groups" ON "groups"."id" = "posts"."group_id"
INNER JOIN "memberships" ON "memberships"."group_id" = "groups"."id"
INNER JOIN "users" ON "users"."id" = "memberships"."user_id"
WHERE "memberships"."user_id" = 1
我想这样查询:
SELECT posts.* FROM posts
INNER JOIN memberships ON memberships.group_id = posts.group_id
WHERE memberships.user_id = 1
如何在不使用原始SQL的情况下做到这一点?
How can I do this without using raw SQL?
推荐答案
类似这样的东西为您工作,尽管它需要混入一些原始SQL
something like this should work for you, although it requires mixing in a little raw SQL
Post
.joins("INNER JOIN memberships ON memberships.group_id = posts.group_id")
.where(:memberships => {:user_id => current_user.id})
这篇关于带有ActiveRecord和Rails 3的复杂JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文