evuez
evuez

Reputation: 3387

Chaining scopes and accessing other objects

I have to models, Library and 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

Now if I chain the scopes like this Library.first_scope.second_scope, the debug for the first one returns the list of existing books, which is what I would expect, but the second one returns me the list of existing libraries, as if I did logger.debug Library.all.entries.

Why is that? Why can I access the Book collection in the first scope, but not in the second one? And how could I access the Book collection in the second scope?

Upvotes: 0

Views: 79

Answers (1)

evuez
evuez

Reputation: 3387

I ended up using Moped, which seems to work fine... No idea why though.

scope :second_scope, -> do
  logger.debug Book.collection.find.first  # Returns a Book, yay!
  where(name: "Bar")
end

Upvotes: 0

Related Questions