I have a an method that retrieves Groups that are present in certain areas. Groups are given a country_id, region_id and city_id
The UI gives three select boxes to choose a country, a region from that country and then a city from that region. To find all groups in a particular city, I have this code:
@groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
This all works fine, but I also want it to find all groups in an area when the lower criteria isn’t specified. For example, If a country and region are given, but not city, I’d like to find it by the region.
What I’m doing is this:
if !params[:city_id].nil?
@groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
else
if !params[:region_id].nil?
@groups = Group.find(:all, :conditions => {:region_id => params[:region_id]})
else
@groups = Group.find(:all, :conditions => {:country_id => params[:country_id]})
end
end
This works perfectly well, but it seems like it’s a little inefficient. Am I doing it the best way or can I streamline a little?
One idea I had was to have a single find checking against all parameters, but I could not work out how to effectively ‘ignore’ parameters that were nil – my main thought was to check which ones were not set and set them to something like ‘*’ or ‘true’, but that’s not how SQL plays the game.
Sounds like a job for named scopes:
This establishes some simple scopes for restricting the Group records. Presumably you have indexed your database properly so these are quick to resolve.
The controller is much easier to implement then:
Generally you should be testing for .blank? instead of .nil? as some form elements can send in empty results, such as a select with something akin to “All” as the default.