What inverse_of does mean in mongoid?

后端 未结 1 1563

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

相关标签:
1条回答
  • 2021-01-31 05:14

    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.

    0 讨论(0)
提交回复
热议问题