与ActiveRecord和Rails 3的复杂连接



我有以下模型:

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的情况下做到这一点?

通过从调用中删除未使用的连接,您可以在不更改模型的情况下更接近:

Post.joins(group: :memberships).where(memberships: { user_id: 1 })

编译成SQL

SELECT "posts".* FROM "posts"
INNER JOIN "groups" ON "groups"."id" = "posts"."group_id"
INNER JOIN "memberships" ON "memberships"."group_id" = "groups"."id" 
WHERE ("memberships"."user_id" = 1)

像这样的东西应该可以为您工作,尽管它需要混合一些原始SQL

Post
  .joins("INNER JOIN memberships ON memberships.group_id = posts.group_id")
  .where(:memberships => {:user_id => current_user.id})

相关内容

  • 没有找到相关文章

最新更新