I have a location object so location.nearbys get all the locations near location. But I want to limit the results to 5. That I am doing with location.nearbys.limit(5) , but the problem is when there are no nearby location I get an error message . It says limit cant be used on empty array []. So, what's the solution. I can use.
location = location.nearbys
location = location.nearbys.limit(5) unless location.empty?
Do I have better ways to do this ? I am using mongoid , rails 3.0.7 , ruby 1.9.2 .
The problem is that rubygeocoder returns a ActiveRecord::Relation
if successful, but an empty Array
on failure. And Ruby's Array does not respond to limit
, so my tip is to use first(number)
instead of limit(number)
, which will work with both results.
Found out, that the best solution of this problem is to use take(5)
which will work both on Mongoid::Criteria
objects and Ruby Array
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With