inverse_of:nil是什么意思



我知道inverse_of的作用,但我不理解inverse_of:nil。例如,

class Book
include Mongoid::Document
belongs_to :author, inverse_of: nil
end
class Author
include Mongoid::Document
end

作者和书之间没有关联。使用作者和书籍可能是一个不好的例子,但我希望你明白这个想法。我看到inverse_of: nil用了很多。所以想了解它。

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

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

传统案例:

# 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

进一步阅读:http://dmitrypol.github.io/mongo/2016/12/05/habtm-inverse-nil.html#traditional-has_and_belongs_to_many

最新更新