Reputation: 301
min_age = params[:min_age]
max_age = params[:max_age]
@users = User.find(:all, :conditions => [" years >= ? AND years <= ? ", min_age, max_age])
This is the controller method for a search feature. As you can see I wish to search by age range. This works for all max_age values up to 99, but when the max_age exceeds 99 the search returns no results when it should. I don't really expect many people beyond 99 but I am curious why this is happening. The age is a string.
Upvotes: 1
Views: 109
Reputation: 23450
Mark Byers has the right answer. So it should be accepted.
But you should know, this is the kind of thing you should be using a named scope for.
In user.rb
named_scope :ages_in_range, lambda {|min, max|
{:conditions => ["years >= ? AND years <= ?", min, max]}
}
Now in your controller:
@users = User.ages_in_range(min_age,max_age)
Upvotes: 2
Reputation: 838226
It's because "100" comes before "20" when you compare alphanumerically as strings do. Change age
to an integer as it should be, and it will work fine.
Upvotes: 3