What inverse_of does mean in mongoid?

2019-03-08 20:22发布

问题:

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.