What inverse_of does mean in mongoid?

ぐ巨炮叔叔 提交于 2019-12-20 08:57:44

问题


What inverse_of does mean in mongoid associations? What I can get by using it instead of just association without it?


回答1:


In a simple relation, two models can only be related in a single way, and the name of the relation is automatically the name of the model it is related to. This is fine in most cases, but isn't always enough.

inverse_of allows you to specify the relation you are referring to. This is helpful in cases where you want to use custom names for your relations. For example:

class User
  include Mongoid::Document
  has_many :requests, class_name: "Request", inverse_of: :requester
  has_many :assignments, class_name: "Request", inverse_of: :worker
end

class Request
  include Mongoid::Document
  belongs_to :requester, class_name: "User", inverse_of: :requests
  belongs_to :worker, class_name: "User", inverse_of: :assignments
end

In this example, users can both request and be assigned to tickets. In order to represent these two distinct relationships, we need to define two relations to the same model but with different names. Using inverse_of lets Mongoid know that "requests" goes with "requester" and "assignments" goes with "worker." The advantage here is twofold, we get to use meaningful names for our relation, and we can have two models related in multiple ways. Check out the Mongoid Relations documentation for more detailed information.



来源:https://stackoverflow.com/questions/15242047/what-inverse-of-does-mean-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!