我明白inverse_of做什么,但我不理解inverse_of: 0。例如,
class Book
include Mongoid::Document
belongs_to :author, inverse_of: nil
end
class Author
include Mongoid::Document
end作者和书之间没有任何联系。使用作者和书可能是一个不好的例子,但我希望你有这个想法。我看到inverse_of: nil经常使用。所以想要理解它。
发布于 2018-10-25 15:37:01
它涵盖了没有定义相反关系的Mongoid特定情况。
在您的示例中,如果inverse_of: nil class Author不使用has_many :books,则需要在中包含has_many :books。
传统案例:
# app/models/book.rb
class Book
field :title
belongs_to :author
end
# app/models/author.rb
class Author
field :name
has_many :books
end没有对立的关系案件:
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
https://stackoverflow.com/questions/52992782
复制相似问题