0

给定

文档:

has_many :shares
has_many :groups, :through => :shares

用户:

has_many :memberships
has_many :groups, :through => :memberships

团体:

has_many :memberships
has_many :users, :through => :memberships

has_many :shares
has_many :documents, :through => :shares

我只需要显示给定用户实例 current_user 的文档。

@documents = current_user.groups.documents不削减它。

我如何才能过滤到仅与用户至少有一个共同组的文档?

4

2 回答 2

1

您可以使用单个查询来执行此操作:

Document.includes(:shares => { :group => :users }).where('users.id' => current_user.id)

生成的 SQL(用于current_user.id = 1):

SELECT "documents"."id" AS t0_r0, "documents"."created_at" AS t0_r1,
  "documents"."updated_at" AS t0_r2, "shares"."id" AS t1_r0,
  "shares"."group_id" AS t1_r1, "shares"."document_id" AS t1_r2,
  "shares"."created_at" AS t1_r3, "shares"."updated_at" AS t1_r4,
  "groups"."id" AS t2_r0, "groups"."created_at" AS t2_r1,
  "groups"."updated_at" AS t2_r2, "users"."id" AS t3_r0,
  "users"."created_at" AS t3_r1, "users"."updated_at" AS t3_r2
  FROM "documents"
  LEFT OUTER JOIN "shares" ON "shares"."document_id" = "documents"."id"
  LEFT OUTER JOIN "groups" ON "groups"."id" = "shares"."group_id"
  LEFT OUTER JOIN "memberships" ON "memberships"."group_id" = "groups"."id"
  LEFT OUTER JOIN "users" ON "users"."id" = "memberships"."user_id"
  WHERE "users"."id" = 1

请注意,通过使用includes而不是joins,仅返回不同的结果(因此无需调用uniq结果)。请参阅:不同的连接 Rails

于 2012-11-22T14:40:58.293 回答
0

关于什么

docs = []
current_user.groups.uniq.each do |group|
   docs << group.documents
end
docs
于 2012-11-23T11:12:52.793 回答