首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >inverse_of:零是什么意思?

inverse_of:零是什么意思?
EN

Stack Overflow用户
提问于 2018-10-25 15:16:55
回答 1查看 1K关注 0票数 2

我明白inverse_of做什么,但我不理解inverse_of: 0。例如,

代码语言:javascript
复制
class Book
  include Mongoid::Document
  belongs_to :author, inverse_of: nil
end

class Author
  include Mongoid::Document
end

作者和书之间没有任何联系。使用作者和书可能是一个不好的例子,但我希望你有这个想法。我看到inverse_of: nil经常使用。所以想要理解它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-25 15:37:01

它涵盖了没有定义相反关系的Mongoid特定情况。

在您的示例中,如果inverse_of: nil class Author不使用has_many :books,则需要在中包含has_many :books

传统案例:

代码语言:javascript
复制
# app/models/book.rb
class Book
  field :title
  belongs_to :author
end

# app/models/author.rb
class Author
  field :name
  has_many :books
end

没有对立的关系案件:

代码语言:javascript
复制
class Book
  field :title
  belongs_to :author, inverse_of: nil
end

# here we use `get_books` instead of `has_many :books`
# so we need `inverse_of: nil` so Mongoid doesn't get confused
class Author
  field :name
  # has_many :books

  def get_books
    Book.in(author_id: self.id)
  end
end

进一步阅读:many

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52992782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档