问题描述
在蒙古语关联中是什么意思?我可以通过使用它而不是没有它的关联来获得什么?
What inverse_of
does mean in mongoid associations? What I can get by using it instead of just association without it?
推荐答案
在简单的关系中,两个模型只能以一种方式关联,并且关系的名称自动是与其关联的模型的名称. .在大多数情况下,这很好,但并不总是足够的.
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
允许您指定要引用的关系.在您要为关系使用自定义名称的情况下,这很有用.例如:
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
在此示例中,用户既可以请求票证,又可以将其分配给票证.为了表示这两个不同的关系,我们需要为相同的模型定义两个关系,但使用不同的名称.使用inverse_of
可使Mongoid知道请求"与请求者"一起使用,而分配"与工人"一起使用.这里的好处是双重的,我们可以为关系使用有意义的名称,并且我们可以使两个模型以多种方式关联.请查看 Mongoid关系文档以获取更多详细信息.
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.
这篇关于蒙古语中的inverse_of是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!