与 proc for mongoid 的关联

Association with proc for mongoid

我在 Mongoid 的源代码中看到没有过程可以发送到关联方法,实现以下 AR 与 Mongoid 关联的最佳实践是什么:

class Task
  ...

  belongs_to :creator, ->{where(type: :manager)}, class_name: "User"
  belongs_to :acceptor, ->{where(type: :acceptor)}, class_name: "User"
end

看来我找到答案了。 Mongoid 中的关系方法接受块作为第三个参数。

  belongs_to :creator, class_name: "User", inverse_of: :created_tasks do
    ->{ where(type: :manager)}
  end

 belongs_to :executor, class_name: "User", inverse_of: :accepted_tasks do
   ->{where(type: :acceptor)}
 end

至少对于 has_many 关系,我在使用 mongo 中的默认过滤器时遇到了问题,所以我想知道您的答案是否真的适用于 belongs_to .这对我来说一直在 has_many 方面正常工作,所以我认为这对其他人也可能是一个有用的答案:

 belongs_to :user do
   def creator
     where(type: :manager)}
   end

   def executor
     where(type: :acceptor)
   end
 end

然后可以通过说 task.user.acceptedtask.user.created 等来访问它们,但是我一直无法弄清楚如何为整体关系实际设置默认过滤。