我有以下型号:
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})