Reputation: 2742
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 .
Upvotes: 4
Views: 877
Reputation: 5416
This should work, even if you get an empty array.
location = location.nearbys
location = location[0..4]
Upvotes: 2
Reputation: 12397
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.
Upvotes: 6
Reputation: 1486
I believe location.nearbys is a collection. You can impose the limit on collection itself as follows:
has_many locations, :limit => 5
In this way you retrieve only required data from the DB and also no hassle of rescue
or try
.
Upvotes: 0
Reputation: 11628
One way to write it would be location.nearbys.try(:limit, 5)
More on Object#try
Upvotes: 0
Reputation: 14718
Not sure if better - but alternatively you maybe be able to wrap it in a rescue block which would also give you the option on doing something else when the result is empty
Upvotes: 2