What are the tradeoffs of using mongoid has_and_belongs_to_many with inverse_of

The docs say you can use inverse_of: nil but don't really describe a use case: http://mongoid.org/en/mongoid/docs/relations.html#has_and_belongs_to_many

I assume this is useful when one object has a LOT of the other, so you can just skip this side completely with inverse_of nil and save some storage space correctly?

So for example:

class Post has_and_belongs_to_many :tags end class Tag has_and_belongs_to_many :posts, inverse_of: nil end 

A tag can belong to hundreds or thousands of posts, but a post probably has only 5 tags or so.

So is this a good option for this? I guess you can still do

 tag.posts 

etc., as usual, and the main compromise is that it changes the request:

 Post.find(tag.post_ids) 

in

 Post.where(tag_ids: tag.id) 

If you have a pointer to tag_ids, it looks like it will still be pretty fast. So perhaps the best thing is something like:

 class Post has_and_belongs_to_many :tags, index: true end class Tag has_and_belongs_to_many :posts, inverse_of: nil end 

I just want to test my thoughts.

+7
source share
1 answer

Of course, you used the use case correctly, but it seems that the example has been reworked. Your models should look like this:

 class Post has_and_belongs_to_many :tags, inverse_of: nil, index: true end class Tag # you don't want this side as a tag can be related to 1000s of posts end 

You can use associations from messages, but for tags you will need to create queries yourself.

 post.tags # get tags for a post Post.where(tag_ids: tag.id) # find posts for a tag 
+7
source

All Articles