Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP


Mongoid: .near doesn't work with scopes #98

gjb83 opened this Issue · 8 comments

9 participants



  • Ruby 1.9.2
  • Rails 3.1.0.rc5
  • MongoDB 1.8.2
  • Mongoid 2.0.2

.near works as expected when called against a model:

> Item.near('London', 50)
=> #<Mongoid::Criteria
  selector: {:coordinates=>{"$nearSphere"=>[-0.1262362, 51.5001524], "$maxDistance"=>0.012630230737833089}},
  options:  {},
  class:    Item,
  embedded: false>

However, the following error occurs if I call .near against a scope:

> i = Item.all
=> #<Mongoid::Criteria
  selector: {},
  options:  {},
  class:    Item,
  embedded: false>

> i = i.near('London', 50)
ArgumentError: wrong number of arguments (2 for 1)
    from /usr/local/Cellar/ruby/1.9.2-p180/lib/ruby/gems/1.9.1/gems/mongoid-2.0.2/lib/mongoid/criterion/inclusion.rb:137:in `near'
    from (irb):7
    from /usr/local/Cellar/ruby/1.9.2-p180/lib/ruby/gems/1.9.1/gems/railties-3.1.0.rc5/lib/rails/commands/console.rb:45:in `start'
    from /usr/local/Cellar/ruby/1.9.2-p180/lib/ruby/gems/1.9.1/gems/railties-3.1.0.rc5/lib/rails/commands/console.rb:8:in `start'
    from /usr/local/Cellar/ruby/1.9.2-p180/lib/ruby/gems/1.9.1/gems/railties-3.1.0.rc5/lib/rails/commands.rb:40:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

It appears that the .near method from geocoder is being replaced by the standard Mongoid method.


I'm having the same issue


any update on this?


I ran into this the other day. If you look at the source you can see that the Geocoder .near method is only applied on the base document, not on scopes derived from that document. To get around it barring a real fix you simply need to ensure that your Geocoder .near is always the first scope in your chain. This was a bit ugly in my case but it worked... In other words:

Item.awesome.near #fails
Item.near.awesome #works

Is the geocoded model embedded?

I believe that error is from calling Mongoid::Criteria#near which has a totally different signature than the geocoder near method. Additionally, the Mongoid method does not do any $maxDistance calculations.


I'm having the issue with embedded models that are geocoded. On SO:

Is there a workaround?


@bdmac (or anyone else): If you know how to fix, would be fantastic if you could submit a pull request.


I need to find out how to get a list of objects that are near me and are geocoded..

e.g. Item.geocoded.near(address, 5)

Apparently it wont work that way, and @bdmac, your solution wont work for this because a query failure would occur.


undefined method `geocoded' for Post:Class


where is the method 'geocoded', i can't find it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.