Created
November 17, 2010 07:07
-
-
Save doxavore/703090 to your computer and use it in GitHub Desktop.
Using Mongoid's scoping mechanisms can really add up... not always in a good way.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example implementation, ignoring the less important details: | |
class MyTree | |
include Mongoid::Document | |
include Mongoid::Tree | |
referenced_in :account, :inverse_of => :trees | |
field :slug | |
scope :slugged, lambda { |s, options={}| where(options.merge(:slug => s)).first } | |
def self.with_full_path(path) | |
parts = path.split('/') | |
# Any query after this using "where" or a scope includes :parent_ids=>{"$size"=>1} in the Mongo query: | |
folder = slugged(parts.shift, :parent_ids.size => 1) | |
parts.inject(folder) do |parent, part| | |
# Don't want the :parent_ids.size part here, but it's being included | |
slugged(part, :parent_id => parent.id) | |
end | |
end | |
end | |
# Called like this: | |
acct = Account.first | |
acct.trees.with_full_path("first/second") | |
# Mongoid::Finders has the following, which I think is the cause of the issue, since nothing ever "unbuilds" my criteria 'where' addition: | |
module Mongoid | |
module Finders | |
# Initializes and returns the current scope stack. | |
def scope_stack | |
scope_stack_for = Thread.current[:mongoid_scope_stack] ||= {} | |
scope_stack_for[object_id] ||= [] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment