使用mongoid的has_and_belongs_to_many和inverse_of有什么权衡

Bri*_*ong 7 mongoid

在文档中它说你可以使用inverse_of:nil但是并没有真正描述用例:http: //mongoid.org/en/mongoid/docs/relations.html#has_and_belongs_to_many

我假设它在一个对象有很多另一个对象的情况下很有用,所以你可以完全用inverse_of nil跳过那一边并节省一些存储空间吗?

例如:

class Post
  has_and_belongs_to_many :tags
end

class Tag
  has_and_belongs_to_many :posts, inverse_of: nil
end
Run Code Online (Sandbox Code Playgroud)

标签可能属于数百或数千个帖子,但帖子可能只有5个标签左右.

那么这是一个很好的用例吗?我想你仍然可以做到

tag.posts
Run Code Online (Sandbox Code Playgroud)

像正常一样,主要的权衡是它改变了以下的查询:

Post.find(tag.post_ids)
Run Code Online (Sandbox Code Playgroud)

Post.where(tag_ids: tag.id)
Run Code Online (Sandbox Code Playgroud)

如果你有一个tag_ids的索引,它似乎仍然会很快.所以也许最好的是:

class Post
  has_and_belongs_to_many :tags, index: true
end

class Tag
  has_and_belongs_to_many :posts, inverse_of: nil
end
Run Code Online (Sandbox Code Playgroud)

只是想检查一下我的想法.

rub*_*ish 7

你当然得到了正确的用例,但是似乎重新设计了一些例子.您的模型应如下所示:

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
Run Code Online (Sandbox Code Playgroud)

您可以使用帖子中的关联,但对于标签,您必须自己创建查询.

post.tags                    # get tags for a post
Post.where(tag_ids: tag.id)  # find posts for a tag
Run Code Online (Sandbox Code Playgroud)