链接范围和访问其他对象
Chaining scopes and accessing other objects
我必须建模,Library
和 Book
。
class Library
include Mongoid::Document
field :name, type: String
has_many :books
scope :first_scope, -> do
logger.debug Book.all.entries
where(name: "Foo")
end
scope :second_scope, -> do
logger.debug Book.all.entries
where(name: "Bar")
end
end
class Book
include Mongoid::Document
field :title, type: String
belongs_to :library
end
现在,如果我像这样链接范围 Library.first_scope.second_scope
,第一个的调试 returns 现有书籍的列表,这是我所期望的,但是第二个 returns 我现有库的列表,就好像我做了 logger.debug Library.all.entries
.
这是为什么?为什么我可以在第一个范围内访问 Book
集合,但不能在第二个范围内访问?我如何访问第二个范围内的 Book
集合?
我最终使用了 Moped,它似乎工作正常......虽然不知道为什么。
scope :second_scope, -> do
logger.debug Book.collection.find.first # Returns a Book, yay!
where(name: "Bar")
end
我必须建模,Library
和 Book
。
class Library
include Mongoid::Document
field :name, type: String
has_many :books
scope :first_scope, -> do
logger.debug Book.all.entries
where(name: "Foo")
end
scope :second_scope, -> do
logger.debug Book.all.entries
where(name: "Bar")
end
end
class Book
include Mongoid::Document
field :title, type: String
belongs_to :library
end
现在,如果我像这样链接范围 Library.first_scope.second_scope
,第一个的调试 returns 现有书籍的列表,这是我所期望的,但是第二个 returns 我现有库的列表,就好像我做了 logger.debug Library.all.entries
.
这是为什么?为什么我可以在第一个范围内访问 Book
集合,但不能在第二个范围内访问?我如何访问第二个范围内的 Book
集合?
我最终使用了 Moped,它似乎工作正常......虽然不知道为什么。
scope :second_scope, -> do
logger.debug Book.collection.find.first # Returns a Book, yay!
where(name: "Bar")
end