通过Rails中的关联将范围添加到has_many

时间:2014-05-16 16:22:47

标签: ruby-on-rails ruby activerecord associations scopes

我有一个由Project模型加入的UserMembership模型。我想要检索一个项目的成员,除了一个用户。

project.members.where.not(id: current_user)

Like this answer,我想使用范围:

class User < ActiveRecord::Base
  scope :except, ->(user) { where.not(id: user) }
end

但这不起作用。

p.members.except(User.find(1))
User Load (1.0ms)
  SELECT "users".* FROM "users"
  WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]

User Load (0.4ms)
  SELECT "users".* FROM "users"
  INNER JOIN "memberships" ON "users"."id" = "memberships"."user_id"
  WHERE "memberships"."project_id" = $1  [["project_id", 2]]

正如您所看到的,这导致两个查询,而不是一个。并且返回所有成员,而不考虑排除。

为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

尝试将范围重命名为其他内容,例如 except_for all_except 。名称除外已被active_record

使用

http://api.rubyonrails.org/classes/ActiveRecord/SpawnMethods.html#method-i-except

你也得到2个查询,因为你正在做User.find(1),这导致了第一个查询。