sql – 与ActiveRecord和Rails 3的复杂JOIN

前端之家收集整理的这篇文章主要介绍了sql – 与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

我必须找到属于用户所属组的所有帖子.我用这种方法做到了:

@post = Post.joins(:group => {:memberships => :user}).where(:memberships => {:user_id => current_user.id})

但它会产生效率低下的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的情况下执行此操作?

解决方法

这样的东西应该适合你,虽然它需要混合一点原始sql
Post.joins("INNER JOIN memberships ON memberships.group_id = posts.group_id").where(:memberships => {:user_id => current_user.id})

猜你在找的MsSQL相关文章